serialize form to json and store in the cookie

烈酒焚心 提交于 2020-01-03 04:53:10

问题


i want to store form on clientside, in json in cookie, after that deserialize it back to form. what i'm doing:

serialization to JSON:

function formToJSON(selector) {
    var form = {};
    $(selector).find(':input[name]:enabled').each(function () {
        var self = $(this);
        var name = self.attr('name');

        if (name.indexOf('TextBox', 0) == 0) {
            if (form[name]) {
                form[name] = form[name] + ',' + self.val();
            }
            else {
                form[name] = self.val();
            }
        }
    });

    return form;
}

then on form change, i'm trying to save form to cookie:

 $('#form1 :input').change(function () {

    var eba = formToJSON($('#form1'));

    $.cookie.set('fo', eba, {json:true});
    var a = $.cookie.get('fo',true);
    alert(a);


    //$.cookie.set('form123', { "ksf": "saf", "tt": "" }, { json: true });
    //var b = $.cookie.get('form123', true);
    //alert(JSON.stringify(b));
});

in debugger - eba is json object, but alert(a) gives null. commented code works, this json serialized, and i'm gettin it from cookies. but why code doesnt work for form??? cookie plugin taken from jquery.com


回答1:


Use this library to stringify/parse JSON http://json.org/js.html

remember that there is an approx 4KB size limit on cookies , http://support.microsoft.com/kb/306070




回答2:


AFAIK browser cookies cannot be read using javascript(except for your own domain), to prevent Cross Site Reeuqest Forgery But you can still set them.



来源:https://stackoverflow.com/questions/5458736/serialize-form-to-json-and-store-in-the-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!