1

I'm quite new to jQuery, and I'm trying to get the jQuery plugin, jquery.cookie.js to write a cookie, and then redirect based on the cookie value. Here's an outline of what I'm trying to accomplish:

Upon landing on a splash page, the user selects their language preference. They can also check a "remember me" checkbox, which writes the cookie lang-pref with a value of either en or fr. Upon future visits, visitors are redirected to either an English homepage or a French homepage.

Here's my code for writing the cookie:

$(function() 
{
    $("#en").change(function() //#en is the id of the checkbox
    {
        if ($(this).is(":checked"))
        $.cookie('mem', 'en', { expires: 3652 }); // mem is the cookie name, en is the value
    })
});

And here is the code to read the cookie, which I'm reasonably sure I've screwed up, as the redirect doesn't work. I'm not sure how to fix it, though:

$(function() {
    if ($.cookie('mem'))
    $(location).html ("window.location.href = 'http://www.mysite.com/home-en.php'");
});

I've looked over the docs for this plugin, but I'm still not sure how to use the actual cookie's value to perform actions: the examples given on the project's GitHub page, for example, shows how to read a cookie, simply by doing what I've done in the code above.

Long story short, I can't figure out how to read the value of a cookie, and then use said value to perform a redirect.

4

2 回答 2

7

过度烹饪的简单案例

$(function() {
    if ($.cookie('mem')) window.location.href = 'http://www.mysite.com/home-en.php';
});
于 2013-01-05T23:02:14.097 回答
2

cookie 的值由$.cookie('mem'). 要考虑英语和法语重定向(或任何未来的语言值),您可以执行以下操作:

$(document).ready(
     function() {
         var language_preference = $.cookie('mem');
         if (language_preference) {
             window.location.href = 'http://www.mysite.com/home-'+language_preference+'.php';
         }
     }
);

但是,请注意这种语言检测和重定向通常在服务器端完成。在 PHP 中,设置 cookie 后,可以在全局变量中访问它$_COOKIE请参阅PHP 手册中的文档。

例如,您可以使用 PHP 在服务器端执行此操作,而不是在另一个页面的 JS 中执行重定向:

if ($_COOKIE['mem']) :
    header('Location: http://www.mysite.com/home-'.$_COOKIE['mem'].'.php');
    exit;
endif;

这种方法的主要优点是用户只需通过一个启动页面即可到达主页,而不是两个。

于 2013-01-05T23:19:34.737 回答