简体   繁体   English

动态切换语言PHP,Javascript,jQuery UI

[英]Dynamically switching language PHP,Javascript, jQuery UI

I recently started implementing language options for my website. 我最近开始为我的网站实施语言选项。 Here is how it basically works: 基本上是这样的:

if(isset($_GET['lang']))
{
    $langr= $_GET['lang'];
    $_SESSION['lang'] = $langr;
    setcookie('lang', $langr, time() + (3600 * 24 * 30));
}
elseif(isset($_SESSION['lang']))
{
    $langr = $_SESSION['lang'];
}
elseif(isset($_COOKIE['lang']))
{
    $langr = $_COOKIE['lang'];
}
else
{
    $langr = 'en';
}
switch ($langr) 
{
  case 'en':
  $lang_file = $_SERVER['DOCUMENT_ROOT']."/includes/lang/en.php";
     break;
  case 'fr':
  setlocale (LC_ALL, 'fr_FR.utf8','fra'); 
  $lang_file = $_SERVER['DOCUMENT_ROOT']."/includes/lang/fr.php";
     break;

  default:
  $lang_file = $_SERVER['DOCUMENT_ROOT']."/includes/lang/en.php";

}
include_once $lang_file;

It loads the appropriate language file at the top of every page in my website. 它将适当的语言文件加载到我网站上每个页面的顶部。 However, issues starting coming out when using jQuery's UI datepicker. 但是,当使用jQuery的UI datepicker时,问题开始出现。 I found a regional settings file for the datepicker online and have created a separate file for it : 我在线找到了日期选择器的区域设置文件,并为此创建了一个单独的文件:

///jquery.ui.datepicker-fr.js  file

jQuery(function($){
    $.datepicker.regional['fr'] = {
        closeText: 'Fermer',
        prevText: 'Précédent',
        nextText: 'Suivant',
        currentText: 'Aujourd\'hui',
        monthNames: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
            'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
        monthNamesShort: ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin',
            'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
        dayNames: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
        dayNamesShort: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
        dayNamesMin: ['D','L','M','M','J','V','S'],
        weekHeader: 'Sem.',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['fr']);
});

The issue is I need to dynamically load jquery.ui.datepicker-fr.js whenever a language change is detected so that my datepicker switches to french. 问题是,每当检测到语言更改时,我就需要动态加载jquery.ui.datepicker-fr.js以便我的日期选择器切换为法语。 What I was thinking is creating a PHP function that I would put in my <head> that would echo out my file, but the problem with that is that not all my web pages are PHP and I don't find this a very effective method. 我当时在想创建一个PHP函数,该函数将放入我的<head> ,该函数会回显我的文件,但是问题在于,并非我的所有网页都是PHP,并且我认为这不是一种非常有效的方法。 Any other ideas on how to do this? 关于如何执行此操作还有其他想法吗?

You need to put a check in your header.php which will goes like that: 您需要在header.php中进行检查,如下所示:

<script type="text/javascript>" src="/js/<?php if($_SESSION['lang'] == "en"){ echo 'datepicker-en.js'}else echo 'datepicker-fr.js'; ?>"></script>

So it will automatically detect the datepicker file according to your language parameter. 因此,它将根据您的语言参数自动检测日期选择器文件。

我会这样做,有一个单独的PHP文件负责获取正确的JS文件,这样您也可以在计划HTML页面中使用它...

<script type="text/javascript" src="/getCorrectJsFile.php"></script>

What do you think of this approach? 您如何看待这种方法?

function getBaseURL()
{
    var url = location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));
    if (baseURL.indexOf('http://localhost') != -1)
    {
        var url = location.href; 
        var pathname = location.pathname;  
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);
        return baseLocalUrl + "/";
    }
    else
    {
        return baseURL + "/";
    }
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
   }
}


function getLang()
{
    var lang = getCookie("lang");
    switch(lang)
    {
        case "fr":
            document.write("<script src='"+getBaseURL()+"js/lang/jquery.ui.datepicker-"+lang+".js'></script>");
            break;
        default:
            document.write("");
    }
}
getLang();

The functions would be located in a common js file and I would call the getLang() function on all of my pages... 这些函数将位于一个通用的js文件中,我将在所有页面上调用getLang()函数。

How about using .change() and .post()? 如何使用.change()和.post()呢? You add id of lang to your form where a user can change the language. 您可以在表单中添加lang ID,用户可以在其中更改语言。

$('#lang').change(function(){
           //link to your php file
    var findlangfile = "<?php echo index.php/findlang.php;?>
    $.post(findlangfile, {
        lang: $('#lang').val(),
    }, function(response){
        // you do things
    });
    return false;
});

You could use jQuery cookie plugin, a good one. 您可以使用jQuery cookie插件,一个很好的插件。 Then do same procedure with jQuery as with php. 然后使用jQuery和php执行相同的过程。 If language supplied as url parameter - set cookie with the plugin (get language value with the getBaseURL() function above). 如果语言作为url参数提供-使用插件设置cookie(通过上面的getBaseURL()函数获取语言值)。 Otherwise load cookie and then load appropriate javascript file. 否则,加载cookie,然后加载适当的javascript文件。 Something like $('head').append('<script..'); $('head').append('<script..'); should do the task. 应该做的任务。

Make sure to run this whole script on page load with $(function() { /* code here */ }); 确保在页面加载时使用$(function() { /* code here */ });运行整个脚本$(function() { /* code here */ });

Although it's possible to accomplish the task this way, I would highly recommend switching all your pages to php, as it would simplify things like this one. 尽管可以通过这种方式完成任务,但我强烈建议您将所有页面切换到php,因为这样可以简化此类操作。

Improved version of Moeed's answer: Moeed答案的改进版本:



You need to put a check in your header.php which will goes like that: 您需要在header.php中进行检查,如下所示:

 <script src="/js/<?php echo 'datepicker-' . *COOKIE/SESSION VALUE, LIKE en* . '.js'; ?>"></script> 

This will dynamicly select datepicker-???.js where ??? 这将动态选择datepicker-???.js ,其中??? is the value represented by the cookie/session-cookie. 是cookie / session-cookie表示的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM