双语浏览器重定向Javascript

时间:2011-11-28 12:09:20

标签: javascript redirect

我正在尝试将英文浏览器重定向到xyz.com/?lang=en,同时让瑞典浏览器继续xyz.com

我一直在努力:

var type=navigator.appName
if (type=="Netscape")
var lang = navigator.language
else
var lang = navigator.userLanguage

//cut down to first 2 chars of country code
var lang = lang.substr(0,2)

// Swedish
if (lang == "sv")
window.location.replace('????')

// if none of above (default to English or any other)
else
window.location.replace('xyz.com/?lang=en')
</script>

但我不知道如何编写瑞典语网址,因为它不是重定向,因为默认语言是瑞典语...写xyz.com让我进入重定向循环


if ($_REQUEST["lang"] == "en") 
{ 
    echo '<div class="langlight"><a href="http://xyz.com/">Svenska</a></div>';
} 
else 
{
    echo '<div class="langbold"><a href="http://xyz.com/">Svenska</a></div>';

}

if ($_REQUEST["lang"] == "en") 
{
    echo '<div class="langbold"><a href="http://xyz.com/">English</a></div>';
} 
else 
{
    echo '<div class="langlight"><a href="xyz.com/">English</a></div>';
}

    enter code here

2 个答案:

答案 0 :(得分:2)

if (lang !== "sv") {
    window.location.replace(window.location.href + '?lang=en');
}

答案 1 :(得分:0)

您始终会检查navigator

中的语言

这种方式每次页面加载时都会尝试使用更改的URL或非URL来重新加载页面。

您需要设置一个不会重新加载页面的条件。
这应该是在传递URL参数时。

因此,检查查询字符串,如果网址中存在值,则覆盖默认值。

<script type="text/javascript">
    (function(undefined){
        var queryString = {},
            search = window.location.search.substring(1), // read the current querystring
            searchItems = search.length?search.split('&'):[]; //  and split it at the different params if any exist
        for(var i = 0, len = searchItems.length; i < len; i++){ // for each parameter passed
           var parts = searchItems[i].split('='); // split the key/value pair
           queryString[parts[0].toLowerCase()] = parts[1]; // and store it to our queryString variable
        }

       if (queryString.lang === undefined){ // if there is no lang parameter passed do your checking otherwise skip this step completely and use the url lang parameter.
           var type=navigator.appName, lang = ''; 
           if (type=="Netscape") {
               lang = navigator.language.substr(0,2);
           } else {
               lang = navigator.userLanguage.substr(0,2);
           }
           if (lang != "sv"){
               if (searchItems.length){
                   window.location.replace(window.location.href + '&lang=en');
               } else {
                   window.location.replace(window.location.href + '?lang=en');
               }
           }
       }
    }());
</script>

注意:虽然@missingno在对你的问题的评论中提及,但最好是在服务器端处理,而不是在客户端处理。