【问题标题】:Static multilanguage javascript redirection keeps reloading a page静态多语言 javascript 重定向不断重新加载页面
【发布时间】:2016-11-17 22:45:41
【问题描述】:

我希望你能帮助我解决我的问题。我的静态 html 网站上有 3 种语言。我想根据用户的浏览器语言设置重定向用户。

这是我的代码:

    var lang = navigator.language;
if (lang == 'pl'){
    document.location.href = 'index_pl.html';
}
else if (lang == 'fr'){
    document.location.href = 'index_fr.html';
}
else {
    document.location.href = 'index.html';
}
alert(lang); 

问题是每次用户进入网站时,此脚本都会不断刷新/重定向网站。我的问题是如何检查用户浏览器一次,然后将用户重定向到专用网页。

提前致谢。

【问题讨论】:

    标签: javascript jquery html redirect multilingual


    【解决方案1】:

    如果您不希望它继续重定向,则需要检查当前 URL 中的页面。例如:

    var lang = navigator.language;
    var redirectURL = 'index.html';
    
    if (lang == 'pl'){
        redirectURL = 'index_pl.html';
    } else if (lang == 'fr'){
        redirectURL = 'index.html';
    }
    
    if (document.location.pathname.indexOf(redirectURL) == -1) {
        document.location.href = redirectURL;
    }
    

    这会检查重定向 URL 是否不在路径中。

    【讨论】:

    • 感谢您的回答。所有文件都在根目录中,上面的代码正在检查用户浏览器语言是什么,并根据该信息重定向到特定页面。一旦用户被重定向,scipt 再次检查用户语言。 (无限循环)。也许我应该在第一次重定向后向 url 添加一些东西,或者使用 localstorage?
    • 如果您想存储选项的内容,可以使用 localstorage 或 cookie,但您不需要这样做。如果它仍在重定向,则某些内容与路径检查不匹配。注释掉 document.location.href 并输出(alert 或 console.log)它显示的内容。例如:alert(document.location.path+" != /"+redirectURL)
    • 返回未定义!= /index_pl.html 但所有文件都在同一个根目录中
    • 对不起我的错。是路径名。见上文修订。
    • 这可能在服务器上工作,但在本地主机上会返回 E:/filelocation/foldername/index.html != /index_pl.html 我想我必须找到其他解决方案....
    【解决方案2】:

    我想我已经使用 localStorage 解决了这个问题。 代码如下:

    if (localStorage.getItem("visit") == null)
    {
        // Show Welcome message
        var lang = navigator.language;
        if (lang == 'pl'){
            document.location.href = 'index_pl.html';
        }
        else if (lang == 'fr'){
            document.location.href = 'index_fr.html';
        }
        else {
            document.location.href = 'index.html';
        }
    }
    
    localStorage.setItem("visit", new Date());
    

    【讨论】:

    • 这个解决方案的问题是你在设置重定向之后设置日期。我仍然认为你不需要这个。您可以看到我修改后的解决方案,用于检查字符串中的 redirectURL 实例,因此它可以在您的 localhost 上运行。这种方法也可以,但是您需要在重定向之前设置项目。您可以将作为第一项放在 if 语句中。
    猜你喜欢
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2012-06-06
    相关资源
    最近更新 更多