如果cookie为null jquery,则发出设置并重定向用户

时间:2015-01-27 01:41:58

标签: javascript jquery redirect cookies

在我的主页中,我有以下脚本,当用户访问我们的网站时,我们会检查两件事

  1. 如果屏幕尺寸小于800,那么我们会将它们重定向到移动网站

  2. 如果他们来自移动网站,因为他们可以选择从移动网站上的页脚“查看完整网站”,那么我们需要创建一个cookie,以允许个人浏览网站任何中断。

  3. 现在使用以下代码我们遇到了一些问题。我们做的时候一样

    var value = getCookie('example'); 
    

    值始终未定义,如果他们第一次直接浏览网站并且之前的网址不是移动网站,我会指望它。

    但是,如果我直接进入主站点并被定向到移动设备并按“查看完整站点”,则下面的脚本将运行,但是从未创建cookie,因此当我点击主站点上的某个菜单项时并且浏览回主页我被重定向到移动网站,因为cookie的值是不明确的?所以问题是我在这里做错了什么?

    澄清cookie是否为null将它们重定向到移动站点,如果它不为null则不重定向它们允许它们浏览主站点。

    var oldURL = document.referrer;
    
        var value = getCookie('example');
    
        alert(oldURL);
        alert(value); // Always undefined? 
    
        // If this is true they have come from the mobile site
        if (oldURL.indexOf("m.domain") > -1) {
    
            if (value == null) {
                var date = new Date();
                var minutes = 30;
                date.setTime(date.getTime() + (minutes * 60 * 1000));
                $.cookie("example", "Yes", { expires: date });
            }
    
        }
        else { // Otherwise if the screen width is small then 800px wide re-direct them to the mobile site
    
            if (value == null) { // If value is null that means they have come to the main site so re-direct them to the mobile version
                if (screen.width <= 800) {
                    window.location = "m.domain.com";
                }
            }
        }
    
        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);
                }
            }
        }
    

1 个答案:

答案 0 :(得分:0)

好的,设法让它与下面一起工作。

 var oldURL = document.referrer;

    var t = getCookie("fromMobile");

    if (oldURL.indexOf("m.domain") > -1) {
        var date = new Date();
        var minutes = 30;
        date.setTime(date.getTime() + (minutes * 60 * 1000));
        document.cookie = "fromMobile=Yes; expires="+ date.toGMTString() +"; path=/";
    } else {
        if (t == "") {
            if (screen.width <= 800) {
                window.location = "http://m.domain.com";
            }
        }
    }
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
        }
        return "";
    }