Javascript jQuery 反序列化表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6992585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:10:23  来源:igfitidea点击:

jQuery deserialize form

javascriptjquerydeserialization

提问by Tomas

I am using jQuery Serializeto serialize my form elements and would like to deserialize them back. Unfortunately can't find any working jQuery deserializer, any suggestions?

我正在使用jQuery Serialize来序列化我的表单元素,并希望将它们反序列化。不幸的是找不到任何可用的 jQuery 反序列化器,有什么建议吗?

采纳答案by Benjamin Atkin

Half of jQuery Serialize is param(), so half of something that deserializes a query string is going to be a deparam. Unfortunately I haven't been able to find a good standalone deparam. For now I recommend getting the jQuery BBQ libraryand using that. If you don't need the other stuff you can remove them. I read somewhere that Ben Alman (cowboy) planned to extract deparam into its own module.

jQuery Serialize 的一半是param(),所以反序列化查询字符串的一半将是 deparam。不幸的是,我一直无法找到一个好的独立 deparam。现在我建议获取jQuery BBQ 库并使用它。如果你不需要其他东西,你可以删除它们。我在某处读到 Ben Alman(牛仔)计划将 deparam 提取到自己的模块中。

For the rest of deserializing, you'll just need to loop through the object that deparam returns and for each key and value pair in the object, select the form element based on the key, and set the form elements value to the value.

对于反序列化的其余部分,您只需要遍历 deparam 返回的对象,并针对对象中的每个键值对,根据键选择表单元素,并将表单元素值设置为该值。

回答by kflorence

I wrote a version of jQuery.deserializethat supports serialized data generated from the serialize, serializeArray and serializeObject functions. It also supports all form element types, including checkboxes and radio buttons.

我编写了一个jQuery.deserialize版本,它支持从 serialize、serializeArray 和 serializeObject 函数生成的序列化数据。它还支持所有表单元素类型,包括复选框和单选按钮。

回答by Hyman Allan

Try this:

尝试这个:

function deparam(query) {
    var pairs, i, keyValuePair, key, value, map = {};
    // remove leading question mark if its there
    if (query.slice(0, 1) === '?') {
        query = query.slice(1);
    }
    if (query !== '') {
        pairs = query.split('&');
        for (i = 0; i < pairs.length; i += 1) {
            keyValuePair = pairs[i].split('=');
            key = decodeURIComponent(keyValuePair[0]);
            value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
            map[key] = value;
        }
    }
    return map;
}

回答by David Hammond

I was very interested in trying JQuery.deserialize, but it didn't seem to handle checkboxes at all, so it didn't serve my purposes. So I wrote my own. It turned out to be easier than I thought, because the jQuery val() function does most of the work:

我对尝试 JQuery.deserialize 非常感兴趣,但它似乎根本不处理复选框,所以它不符合我的目的。所以我写了我自己的。结果比我想象的要容易,因为 jQuery val() 函数完成了大部分工作:

jQuery.fn.deserialize = function (data) {
    var f = this,
        map = {},
        find = function (selector) { return f.is("form") ? f.find(selector) : f.filter(selector); };
    //Get map of values
    jQuery.each(data.split("&"), function () {
        var nv = this.split("="),
            n = decodeURIComponent(nv[0]),
            v = nv.length > 1 ? decodeURIComponent(nv[1]) : null;
        if (!(n in map)) {
            map[n] = [];
        }
        map[n].push(v);
    })
    //Set values for all form elements in the data
    jQuery.each(map, function (n, v) {
        find("[name='" + n + "']").val(v);
    })
    //Clear all form elements not in form data
    find("input:text,select,textarea").each(function () {
        if (!(jQuery(this).attr("name") in map)) {
            jQuery(this).val("");
        }
    })
    find("input:checkbox:checked,input:radio:checked").each(function () {
        if (!(jQuery(this).attr("name") in map)) {
            this.checked = false;
        }
    })
    return this;
};

You should be able to use this like this:

你应该能够像这样使用它:

$("#myform").deserialize(data);

Where data is a parameter list such as what $("#myform").serialize() would produce.

其中 data 是一个参数列表,例如 $("#myform").serialize() 会产生什么。

It affects all fields in the form, and it will clear the values of fields that are not contained in the data. But you can also pass any selector to affect only specific fields, as you can with the serialize function. E.g.:

它会影响表单中的所有字段,并且会清除数据中未包含的字段的值。但是您也可以传递任何选择器以仅影响特定字段,就像使用序列化函数一样。例如:

$("select").deserialize(data);

回答by user3204597

Bit late on this one, but somebody might find this useful.

这个有点晚了,但有人可能会发现这很有用。

function fetchInput(identifier) {
    var form_data = identifier.serialize().split('&');
    var input     = {};

    $.each(form_data, function(key, value) {
        var data = value.split('=');
        input[data[0]] = decodeURIComponent(data[1]);
    });

    return input;
}

回答by Pehmolelu

I'm not now answering your question but my guess is that you want to serialize it and send back to server and then use the serialized data which is why you have to deserialize it?

我现在没有回答你的问题,但我的猜测是你想序列化它并发送回服务器,然后使用序列化的数据,这就是为什么你必须反序列化它?

If that's the case you should consider using .serializeArray(). You can send it as POST data in ajax, and then access later as well because you will have object.

如果是这种情况,您应该考虑使用 .serializeArray()。您可以在ajax中将其作为POST数据发送,然后也可以稍后访问,因为您将拥有对象。

回答by Ivan

May be a bit late, but perhaps you are looking for something like JQuery.deserialize. Problems: no support for checkboxes or radio buttons.

可能有点晚了,但也许您正在寻找类似JQuery.deserialize 的东西。问题:不支持复选框或单选按钮。

回答by Phil LaNasa

Using Hyman Allan's deparamfunction with jQuery, you can change this line:

在 jQuery 中使用 Hyman Allan 的deparam函数,您可以更改此行:

map[key] = value;

to

$('input[name=' + key + ']').val(value);

Which will load the data back into your form fields.

这会将数据加载回您的表单字段。

回答by Spacefrog

this code returns an array when same key is spotted multiple times in the serialized string

当在序列化字符串中多次发现相同的键时,此代码返回一个数组


    chaine="single=Single1&multiple=Multiple&multiple=Multiple1&multiple=Multiple2&multiple=Multiple3&check=check2&radio=radio1"
    function deserialize(txt){
    myjson={}
    tabparams=chaine.split('&')
    var i=-1;
    while (tabparams[++i]){
    tabitems=tabparams[i].split('=')
    if( myjson[decodeURIComponent(tabitems[0])] !== undefined ){
        if( myjson[decodeURIComponent(tabitems[0])] instanceof Array ){
            myjson[decodeURIComponent(tabitems[0])].push(decodeURIComponent(tabitems[1]))
        }
    else{
       myjson[decodeURIComponent(tabitems[0])]= [myjson[decodeURIComponent(tabitems[0])],decodeURIComponent(tabitems[1])]
            }
        }
    else{
         myjson[decodeURIComponent(tabitems[0])]=decodeURIComponent(tabitems[1]);
        }
    }
    return myjson;
    }

回答by Atul Yadav

Needed all in a single string, which can be stored in maybe COOKIE, and later read and fill the same form with input values.

需要所有在单个字符串中,可以存储在可能的 COOKIE 中,然后读取并使用输入值填充相同的表单。

Input elements seperator: ~(use any seperator)

输入元素分隔符:~ (使用任何分隔符)

Input attributes seperator: |(use any seperator)

输入属性分隔符:| (使用任何分隔符)

input type |input name |input value ~input2 type |input2 name |input2 value

输入类型| 输入名称| 输入值~input2 类型| input2 名称| 输入2值

var formData = '';
$('#form_id').find('input, textarea, select').each(function(i, field) {
    formData += field.type+'|'+field.name+'|'+field.value+'~';
});

Example:

例子:

hidden|vote_id|10~radio|option_id|~radio|option_id|427~radio|option_id|428~