试图保存cookie

时间:2014-02-25 16:51:11

标签: javascript jquery cookies

我正在尝试将查询字符串保存为cookie。我使用查询字符串进行登录,我需要保存查询字符串以在另一页上使用它。由于某种原因,代码无法正常工作。没有cookie的东西,它会做我想要的。但是,当我尝试添加该代码时,它将不再起作用。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
    var QueryString = function() {
        // This function is anonymous, is executed immediately and 
        // the return value is assigned to QueryString!
        var query_string = {};
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            // If first entry with this name
            if (typeof query_string[pair[0]] === "undefined") {
                query_string[pair[0]] = pair[1];
                // If second entry with this name
            } else if (typeof query_string[pair[0]] === "string") {
                var arr = [query_string[pair[0]], pair[1]];
                query_string[pair[0]] = arr;
                // If third or later entry with this name
            } else {
                query_string[pair[0]].push(pair[1]);
            }
        }
        return query_string;
    }();
    setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }
    setCookie("email", QueryString.u, 1);

    setCookie("password", QueryString.p, 1);

    jQuery(function() {
        jQuery('#email').val(QueryString.u);
        jQuery('#password').val(QueryString.p);
        jQuery('#submit').click();
    });
</script>

2 个答案:

答案 0 :(得分:1)

我认为这是由于他的代码出错了,应该不是吗?

var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
        query_string[pair[0]] = pair[1];
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
        var arr = [query_string[pair[0]], pair[1]];
        query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
        query_string[pair[0]].push(pair[1]);
    }
}


function setCookie(cname, cvalue, exdays)
{
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

什么是“QueryString”?

答案 1 :(得分:1)

尝试更改

setCookie(cname,cvalue,exdays)

function setCookie(cname,cvalue,exdays)