简体   繁体   English

如何在jQuery中使用多个值创建cookie

[英]How to make cookie with multiple values in jQuery

I am having some trouble creating and getting a cookie with multiple values inside. 我在创建并获取包含多个值的cookie时遇到了一些麻烦。 Okay, what I would like to do, is to create a cookie with a forms input values in it when a submit button is clicked. 好吧,我想做的是,当单击提交按钮时,在其中创建一个带有表单输入值的cookie。 Then when the same user revisits the site, the form will be autofilled with what the user typed in last time. 然后,当同一用户重新访问该网站时,该表单将自动填充用户上次输入的内容。

My html: 我的HTML:

<form id="formen">
<fieldset>
    <legend>Login</legend>
    <label for="firstname" class="label">Firstname</label>
    <input type="text" name="firstname" id="firstname" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">Lastname</label>
    <input type="text" name="lastname" id="lastname" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">Address</label>
    <input type="text" name="third" id="address" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">City</label>
    <input type="text" name="city" id="city" class="text" maxlength="30" data-sayt-exclude/>
    </br></br>
    <label for="lastname" class="label">Zipcode</label>
    <input type="number" name="zipcode" id="zipcode" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">E-mail</label>
    <input type="email" name="email" id="email" class="text" maxlength="30" />
    </br></br>
    <label for="lastname" class="label">Phone</label>
    <input type="number" name="phone" id="phone" class="text" maxlength="30" />
    </br></br>
    <input type="submit" name="submit" value="Remember Me" id="remember"/>
</fieldset>
</form>

My javascript/jQuery: 我的javascript / jQuery:

$(document).ready(function () {
var date = new Date();
date.setTime(date.getTime() + (60 * 1000));

if ($("#remember").click(function () {
    $.cookie('firstnameCookie', $firstnameVariable.val(), { expires: date });
    $.cookie('lastnameCookie', $lastnameVariable.val(), { expires: date });
    $.cookie('addressCookie', $addressVariable.val(), { expires: date });
    $.cookie('cityCookie', $cityVariable.val(), { expires: date });
    $.cookie('zipcodeCookie', $zipcodeVariable.val(), { expires: date });
    $.cookie('emailCookie', $emailVariable.val(), { expires: date });
    $.cookie('phoneCookie', $phoneVariable.val(), { expires: date });
}));

//set the value of the cookie to the element
var $firstnameVariable = $("#firstname").val($.cookie("firstnameCookie"));
var $lastnameVariable = $("#lastname").val($.cookie("lastnameCookie"));
var $addressVariable = $("#address").val($.cookie("addressCookie"));
var $cityVariable = $("#city").val($.cookie("cityCookie"));
var $zipcodeVariable = $("#zipcode").val($.cookie("zipcodeCookie"));
var $emailVariable = $("#email").val($.cookie("emailCookie"));
var $phoneVariable = $("#phone").val($.cookie("phoneCookie"));
});

This code actually does the trick. 这段代码实际上可以解决问题。 It saves the different input values, and autofills when user revisits the site. 它保存不同的输入值,并在用户重新访问站点时自动填充。

The only problem is that I don't want to create a new cookie for each input value. 唯一的问题是我不想为每个输入值创建一个新的cookie。 Is it possible to create just one cookie with each of the inputs values in it, and get it to autofill the different input fields? 是否可以只使用其中的每个输入值创建一个cookie,并使其自动填充不同的输入字段?

Hope someone can help me! 希望可以有人帮帮我! Can't figure it out.. Thx 无法弄明白.. Thx

Concatenate the form values into a string before saving the cookie and split when you have to assign it. 在保存cookie之前将表单值连接成字符串,并在必须分配时将其拆分。 Those are functions I use to concatenate and split: 这些是我用来连接和拆分的函数:

    var splitQueryString = function (q) {
        var pars = q.split("&");
        var qq = {};
        var i = 0;
        for (i = 0; i < pars.length; i++) {
            var ret = pars[i].toString().split("=");
            qq[ret[0]] = decodeURIComponent(ret[1]);
        }
        return qq;
    };

    var getQueryString = function (pars) {
        var q = '';
        var value;
        var key;
        for (key in pars) {
            if (pars.hasOwnProperty(key)) {
                value = pars[key];
                if (!(value === null)) {
                    q += "&" + key + "=" + encodeURIComponent(value);
                }
            }
        }

        if (q.length > 0) {
            //remove first
            q = q.substr(1);
        }

        return q;
    };

Your code could become something like: 您的代码可能会变成:

    if ($("#remember").click(function () {
        var pars = {};
        pars.firstnameVariable = $firstnameVariable.val();
        pars.lastnameVariable = $lastnameVariable.val();

        var cookie = getQueryString(pars);
        $.cookie('formCookie', cookie, { expires: date });
       }));

  //set the value of the cookie to the element
  var pars = splitQueryString($.cookie("formCookie"));
  var $firstnameVariable = $("#firstname").val(pars.firstnameVariable);
  var $lastnameVariable = $("#lastname").val(pars.lastnameVariable);

Store the data by converting the object to a string 通过将对象转换为字符串来存储数据

var obj = {
    "firstname" : $("#firstname").val(),
    "lastname" : $("#firstname").val()
};
$.cookie('data', JSON.stringify(obj), { expires: date });

And when you read it out: 当你读出来时:

var data = $.cookie("data"),
    obj = data ? JSON.parse(data) : "";
Object.keys(obj).forEach(function(key){
    $("#" + key).val(obj[key]);
});

Personally I would use localstorage and not a cookie. 我个人会使用localstorage而不是cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM