如何使用 Ajax 更改服务器端语言 cookie,如客户端? [英] How to change server side language cookies like client side using Ajax?

查看:28
本文介绍了如何使用 Ajax 更改服务器端语言 cookie,如客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个新闻网站,一个用西班牙语,一个用英语:

es.example.com//西班牙语example.com//英语

但是从主域(英文)我正在集成一个系统,以便能够以另一种语言显示新闻,例如:

example.com/es/url-de-la-noticia/​​//西班牙语

基于该 URL,我创建了一个cookie",用于存储 URL 的语言,即第一个文件夹/子文件夹或目录/es/":

//我自动为子域和西班牙语的 URL 创建 cookie.if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {setcookie ('语言', 'es', time()+60*60*24*365, '/', '.example.com');}

使用此参数,新闻将以西班牙语显示两个站点:es.example.com 子域 es 或西班牙语的 URLs example.com/es/url-de-la-noticia/​​ = es

//我们验证cookie的存在if(isset($_COOKIE['语言'])){//我们打印语言的变量与cookie存储的值一致if($_COOKIE['language']==='en'){$website_title = "|Sitio en español";$lang = 'es';$language = "es";}elseif($_COOKIE['语言']==='es'){$website_title = "|网站英格尔斯";$lang = 'en';$language = "en";}} 别的 {//如果没有cookie,我默认显示英文.$website_title = "|网站英格尔斯";$lang = 'en';$language = "en";}

目前看来一切正常.

但是当我尝试通过ajax更改语言时出现问题,虽然ajax代码确实发送和发送信息,但由于某种原因它没有替换cookie,即如果我点击英文,它不改变它,改变语言.

我想要实现的是语言也可以更改,使用ajax删除或替换服务器端和客户端的cookie:

$(function(){var tnum = 'en';$(document).click(function(e) {$('.language, .more_lang').removeClass('active');});$('.language .current_lang').click(function(e){e.stopPropagation();$(this).parent().toggleClass('active');设置超时(功能(){$('.more_lang').toggleClass('active');}, 5);});$('.more_lang .lang').click(function(){$(this).addClass('selected').siblings().removeClass('selected');$('.more_lang').removeClass('active');var img = $(this).find('img').attr('src');var lang = $(this).attr('data-value');var tnum = lang;$('.current_lang .lang-txt').text(lang);$('.current_lang img').attr('src', img);//if(lang == 'ar'){}});});$(函数(){$(".lang").click(function(e) {e.preventDefault();var language = $(this).attr('data-value');var postData={lang: 语言};var 请求 = $.ajax({方法:'POST',url : 'language.ini.php',数据:postData,数据类型:html"});请求.完成(功能(数据){$(".resultado").html(data);});request.fail(function(jqXHR, textStatus) {alert("发生错误:" + textStatus);});});});

body{保证金:0;填充:0;颜色:#444444;font-family: '新闻周期', sans-serif;}.语{位置:固定;z-索引:1;顶部:20px;左:20px;字体大小:16px;背景:#fff;边框半径:4px;}.current_lang{游标:指针;文本转换:大写;溢出:隐藏;}.lang{填充:10px 15px;}.lang.selected{显示:无;}.lang img,.lang span.lang-txt{显示:内联块;左边距:5px;垂直对齐:中间;}.lang span.lang-txt{位置:相对;顶部:-1px;字体粗细:700;}.lang img{宽度:20px;左边距:0;}.lang 跨度{颜色:#999;字体粗细:400;}.lang span.fa{字体大小:12px;位置:相对;顶部:-1px;左边距:3px;}/*更多语言*/.more_lang{变换:translateY(-20px);不透明度:0;游标:指针;显示:无;-webkit-transition:所有 .3s 立方贝塞尔曲线(.25、1.15、.35、1.15);-moz-transition:所有 .3s 立方贝塞尔曲线 (.25, 1.15, .35, 1.15);-o-transition:所有 .3s 三次贝塞尔曲线(.25, 1.15, .35, 1.15);-ms-transition:所有 .3s 立方贝塞尔曲线 (.25, 1.15, .35, 1.15);过渡:所有 .3s 立方贝塞尔曲线 (.25, 1.15, .35, 1.15);}.language.active .more_lang{显示:块;}.more_lang.active{不透明度:1;变换:translateY(-0px);}.more_lang .lang:hover{背景:#5766b2;颜色:#fff;}.more_lang .lang:悬停跨度{颜色:#fff;}.语言:悬停,.language.active,.content a:悬停{box-shadow:rgba(0,0,0,0.2) 0 5px 15px;-webkit-transition:所有 0.3s 立方贝塞尔曲线(0,.99,.44,.99);-moz-transition:所有 0.3s 立方贝塞尔曲线(0,.99,.44,.99);-o-transition:所有 0.3s 立方贝塞尔曲线(0,.99,.44,.99);-ms-transition:所有 0.3s 立方贝塞尔曲线(0,.99,.44,.99);过渡:所有 0.3s 三次贝塞尔曲线(0,.99,.44,.99);}.language.active .lang{边框底部:1px 实心 #eaeaea;}/*内容*/.内容{宽度:100%;最大宽度:400px;位置:绝对;顶部:50%;左:50%;-ms-transform: translateX(-50%) translateY(-50%);-webkit-transform: 翻译(-50%,-50%);变换:翻译(-50%,-50%);边界半径:2px;填充:20px;-webkit-box-sizing: 边框框;-moz-box-sizing: 边框框;box-sizing: 边框框;文字对齐:居中;}.内容 h1,.内容h2,.内容p{保证金:0;}.内容p{行高:22px;文本对齐:左;边距顶部:15px;}.content div.ct-img{宽度:150px;高度:150px;溢出:隐藏;边界半径:50%;边距:0 自动 10px;}.content div img{高度:100%;位置:相对;左:-30px;}.content a{填充:8px 15px 10px;边框半径:4px;背景:#5766b2;颜色:#fff;文字装饰:无;显示:内联块;边距顶部:25px;位置:相对;溢出:隐藏;}.content a:active{变换:比例(0.9);-webkit-transform: scale(0.9);-moz 变换:比例(0.9);}/*返回时间*/正文[dir="rtl"] .language{右:20px;左:自动;}body[dir="rtl"] .lang span.fa{边距右:3px;左边距:0;}正文[dir="rtl"] .lang .lang-txt{边距右:5px;左边距:0;}body[dir="rtl"] .content div img{左:自动;右:-30px;}body[dir="rtl"] .content p{文本对齐:右;}body[dir="rtl"] .lang span span{向左飘浮;边距右:5px;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="语言"><div class="current_lang"><div class="lang" data-value='en'><img src="https://image.flaticon.com/icons/svg/299/299722.svg"><span class="lang-txt">EN</span><span class="fa fa-chevron-down chevron"></span>

<div class="more_lang"><div class="lang selected" data-value='en'><img src="https://image.flaticon.com/icons/svg/299/299722.svg"><span class="lang-txt">英语<span>(美国)</span></span>

<div class="lang" data-value='es'><img src="https://image.flaticon.com/icons/svg/299/299820.svg"><span class="lang-txt">Español</span>

language.ini.php 文件将负责更改语言,创建各自的 cookie.

解决方案

服务器端 Ajax 调用(修复)

在您的 language.ini.php 中,您必须更改该行:

setcookie('language', 'es', time()+60*60*24*365, '/', 'es.example.com');

到:

 setcookie('language', 'es', time()+60*60*24*365, '/', 'example.com');

因为如果您在标头中指定 cookie 域,它将是 none host-only cookie,并且在您的 example.com 中和 es.example.com 将被使用.

根据RFC6265

Cookie 的工作原理

  1. Cookie 通常由服务器端请求设置,浏览器会保存它们.

  2. 浏览器在每个请求中发送 Cookie.

  3. 服务器可以通过来自浏览器的请求访问 cookie.

Cookie 是必不可少的,因为 Http 是无连接协议,并且服务器想要将数据与客户端相关联并在下一个请求中使用.

首选方案(所需解决方案)

只要您的用户决定以他们喜欢的语言查看您的网站.并且您的服务器不会对它做任何事情(没有控件,没有安全线程).

您可以使用快捷方式.

<块引用>

在客户端设置 Cookie

然后删除 language.ini.php 文件.

您可以通过纯 Javascript 以及当用户尝试在浏览器中导航时执行此操作.他/她的请求将通过已设置的 javascript 的新 cookie 发送.

只是您必须注意不要在 Cookie 上启用 HTTP-Only 标志(这可以防止 Js 操作 Cookie).

Jquery 示例:

$.cookie('language', '', { expires: 365, path: '/', domain: 'example.com' });

你的 js 可以看起来像这样,而不是发送一个 ajax 请求:

$(function() {$(".lang").click(function(e) {e.preventDefault();var language = $(this).attr('data-value');$.cookie('language', language, { expires: 365, path: '/', domain: 'example.com' });});});

I have two news websites, one in Spanish and one in English:

es.example.com // Spanish
example.com // English

But from the main domain (in English) I am integrating a system to be able to show news in another language for example:

example.com/es/url-de-la-noticia/ // Spanish

Based on that URL, I create one ´cookie´ where the language of the URL will be stored, which is the first folder/subfolder or directory ´/es/´:

//I create the cookies automatically for the subdomain and for the URLs in Spanish.
if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {
    setcookie ('language', 'es', time()+60*60*24*365, '/', '.example.com');
}

With this parameter, news will be displayed in Spanish for both the site: es.example.com by the subdomain es or by the URLs in Spanish example.com/es/url-de-la-noticia/ = es

//We verify the existence of the cookie
if(isset($_COOKIE['language'])){
    //We print variables of the language in coincidence of the value that the cookie stores
    if($_COOKIE['language']==='en'){
        $website_title = " | Sitio en español";
        $lang = 'es';
        $language = "es";
    }elseif($_COOKIE['language']==='es'){
        $website_title = " | WebSite Ingles";
        $lang = 'en';
        $language = "en";
    }
} else {
    //In case there is no cookie, I show the English language by default.
    $website_title = " | WebSite Ingles";
    $lang = 'en';
    $language = "en";
}

So far everything seems to be working properly.

But the problem arises when I try to change the language through Ajax, although the Ajax code does send and send information, for some reason it does not replace the cookie, that is, if I click on the English language, it does not change it, the change of language.

What I want to achieve is that the language can also be changed, removing or replacing the cookies both on the server side and the client side using ajax:

$(function(){
    var tnum = 'en';
    
    $(document).click( function(e) {
        $('.language, .more_lang').removeClass('active');
    });

    $('.language .current_lang').click(function(e){
        e.stopPropagation();
        $(this).parent().toggleClass('active');
        setTimeout(function(){
            $('.more_lang').toggleClass('active');
        }, 5);
    });

    $('.more_lang .lang').click(function(){
        $(this).addClass('selected').siblings().removeClass('selected');
        $('.more_lang').removeClass('active');

        var img = $(this).find('img').attr('src');
        var lang = $(this).attr('data-value');
        var tnum = lang;

        $('.current_lang .lang-txt').text(lang);
        $('.current_lang img').attr('src', img);

        //if(lang == 'ar'){}
    });
});

$(function() {
    $(".lang").click(function(e) {
        e.preventDefault();
        var language = $(this).attr('data-value');
        var postData={lang: language};

        var request = $.ajax({
            method : 'POST',
            url    : 'language.ini.php',
            data   : postData,
            dataType: "html"
        });
        request.done(function(data) {
            $(".resultado").html(data);
        });
        request.fail(function(jqXHR, textStatus) {
            alert("Ocurrió un error: " + textStatus);
        });
    });
});

body{
    margin:0;
  padding:0;
  color:#444444;
  font-family: 'News Cycle', sans-serif;
}

.language{
  position:fixed;
  z-index:1;
  top:20px;
  left:20px;
  font-size:16px;
  background:#fff;  
  border-radius:4px;
}

.current_lang{
  cursor:pointer;
  text-transform:uppercase;
  overflow:hidden;
}

.lang{
    padding:10px 15px;
}

.lang.selected{
  display:none;
}

.lang img, 
.lang span.lang-txt{
  display:inline-block;
  margin-left:5px;
  vertical-align:middle;
}

.lang span.lang-txt{
   position:relative;
  top:-1px;
  font-weight:700;
}

.lang img{
  width:20px;
  margin-left:0;
}

.lang span span{
  color:#999;
  font-weight:400;
}

.lang span.fa{
  font-size:12px;
  position:relative;
  top:-1px;
  margin-left:3px;
}


/*more lang*/
.more_lang{
  transform:translateY(-20px);
  opacity:0;
  cursor:pointer;
  display:none;
   -webkit-transition: all .3s cubic-bezier(.25, 1.15, .35, 1.15);
    -moz-transition:    all .3s cubic-bezier(.25, 1.15, .35, 1.15);
    -o-transition:      all .3s cubic-bezier(.25, 1.15, .35, 1.15);
    -ms-transition:     all .3s cubic-bezier(.25, 1.15, .35, 1.15);
    transition:         all .3s cubic-bezier(.25, 1.15, .35, 1.15);
}

.language.active .more_lang{
  display:block; 
}

.more_lang.active{
  opacity:1;
   transform:translateY(-0px);
}

.more_lang .lang:hover{
  background:#5766b2;
  color:#fff;
}

.more_lang .lang:hover span{
  color:#fff;
}

.language:hover,
.language.active,
.content a:hover{
  box-shadow:rgba(0,0,0,0.2) 0 5px 15px;  
  -webkit-transition: all 0.3s cubic-bezier(0,.99,.44,.99);
    -moz-transition:    all 0.3s cubic-bezier(0,.99,.44,.99);
    -o-transition:      all 0.3s cubic-bezier(0,.99,.44,.99);
    -ms-transition:     all 0.3s cubic-bezier(0,.99,.44,.99);
    transition:         all 0.3s cubic-bezier(0,.99,.44,.99);
  
}

.language.active .lang{
  border-bottom:1px solid #eaeaea;
}

/*CONTENT*/
.content{
  width:100%;
  max-width:400px;
  position:absolute;
  top:50%;
  left:50%;
  -ms-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
  border-radius:2px;
  padding:20px;
  -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
  
  text-align:center;
}

.content h1, 
.content h2, 
.content p{
  margin:0;
}

.content p{
   line-height:22px;
  text-align:left;
  margin-top:15px;
}


.content div.ct-img{
  width:150px;
  height:150px;
  overflow:hidden;
  border-radius:50%;
  margin:0 auto 10px;
}

.content div img{
  height:100%;
  position:relative;
  left:-30px;
}

.content a{
  padding: 8px 15px 10px;
   border-radius:4px;
  background:#5766b2;
  color:#fff;
  text-decoration:none;
  display:inline-block;
  margin-top:25px;
  position:relative;
  overflow:hidden;
}

.content a:active{
  transform: scale(0.9);
   -webkit-transform: scale(0.9);
  -moz-transform: scale(0.9);
}

/*RTL*/
body[dir="rtl"] .language{
  right:20px;
  left:auto;
}

body[dir="rtl"] .lang span.fa{
  margin-right:3px;
  margin-left:0;
}

body[dir="rtl"] .lang .lang-txt{
  margin-right:5px;
  margin-left:0;
}

body[dir="rtl"] .content div img{
  left:auto;
  right:-30px;
}


body[dir="rtl"] .content p{
  text-align:right;
}

body[dir="rtl"] .lang span span{
  float:left;
  margin-right:5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="language">
        <div class="current_lang">
            <div class="lang" data-value='en'>
                <img src="https://image.flaticon.com/icons/svg/299/299722.svg">
                <span class="lang-txt">EN</span> 
                <span class="fa fa-chevron-down chevron"></span>
            </div>
        </div>
        <div class="more_lang">    
            <div class="lang selected" data-value='en'>
                <img src="https://image.flaticon.com/icons/svg/299/299722.svg">
                <span class="lang-txt">English<span> (US)</span></span>
            </div>
            <div class="lang" data-value='es'>
                <img src="https://image.flaticon.com/icons/svg/299/299820.svg">
                <span class="lang-txt">Español</span>
            </div>
        </div>
    </div>

The language.ini.php file will be in charge of changing the language, creating their respective cookies.

<?php
    if (isset($_POST['lang'])) {
        $lang = $_POST['lang'] ?: '';
    
        if ($lang === "en") {
            setcookie ('language', 'en', time()+60*60*24*365, '/', 'example.com');
        } elseif ($lang === "es") {
            setcookie ('language', 'es', time()+60*60*24*365, '/', 'es.example.com');
        }
    }
?>

解决方案

Server-Side Ajax Call (Fix)

in your language.ini.php you have to change the line:

setcookie ('language', 'es', time()+60*60*24*365, '/', 'es.example.com');

to :

 setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');

because if you specify domain of cookie in header, it will be none host-only cookie and, in your both example.com and es.example.com will be use.

according to RFC6265

How Cookies Works

  1. Cookies usually will be requested to set by server-side and browser will save them.

  2. The Browser sends Cookie in every Request.

  3. Server can access cookie from the Request from browser.

Cookies Are Essential Since Http is Connection-less Protocol, and Server want to Associate a data to a client and use it in next requests .

A Preferable Scenario (Desired Solution)

as long as your user decide to view your site in which language they prefer. and your server will not doing nothing with it (no controls, no security threads).

you can use a shortcut .

Set The Cookie in Your Client-side

and just remove the language.ini.php file.

you can do this by pure Javascript and when the user try to navigate in browser. his/her requests will be sent via new cookie which javascript has been set.

just you have to be aware TO NOT Enable HTTP-Only Flag on Cookie (Which can prevent Js t manipulate Cookie).

Jquery Example:

$.cookie('language', '', { expires: 365, path: '/', domain: 'example.com' });

instead of sending an ajax request your js can looks like this:

$(function() {
    $(".lang").click(function(e) {
        e.preventDefault();
        var language = $(this).attr('data-value');
        $.cookie('language', language, { expires: 365, path: '/', domain: 'example.com' });

    });
});

这篇关于如何使用 Ajax 更改服务器端语言 cookie,如客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆