2011-11-28 81 views
1

我试图重定向英语浏览器xyz.com/?lang=en,同时让那些瑞典留在xyz.com双语言的浏览器重定向的Javascript

我一直在努力:

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> 

但我不知道该怎么写瑞典的URL,因为它不是重定向,因为默认语言是瑞典语......编写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 
+0

为什么在瑞典的情况下不做任何事情?只是在英语时做重定向,而在瑞典语时不做任何事情。 –

+3

检测浏览器语言的正确方法是检查服务器端的[接受语言HTTP标头](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)。客户端语言检测具有跨浏览器问题,有时仅检测已安装的语言(而不是首选语言) – hugomg

+0

,因为所有瑞典语浏览器都有英语作为辅助语言,可重定向它们 – user1046583

回答

2
if (lang !== "sv") { 
    window.location.replace(window.location.href + '?lang=en'); 
} 
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提到了他对你的问题的评论,这是最好的处理服务器端比客户端。

+0

它worx!谢谢:) – user1046583

+0

噢,有一个问题thoe :(有一个语言切换器在网站上,如果和英语浏览器试图切换到瑞典语脚本将他重定向到英语。是否有解决方法? – user1046583

+0

@ user1046583你可以发布切换器代码吗?或者链接到现场版本的网站..? –