jQuery 序列化和反序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3100297/
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-26 14:52:34  来源:igfitidea点击:

jQuery serialize and unserialize

jquery

提问by James

I want to serialize and un-serialize a form with jQuery.

我想用 jQuery 序列化和反序列化表单。

How can I get all attributes of all elements in a serialized way?

如何以序列化的方式获取所有元素的所有属性?

采纳答案by Pekka

jQuery has a serializefunction.

jQuery 有一个serialize功能。

$("#form").serialize(); // Returns serialized string

Reference: http://api.jquery.com/serialize/

参考:http: //api.jquery.com/serialize/

回答by jAndy

.serialize()will map your input controls that have a nameattribute defined into a standard query string:

.serialize()将映射的是有你的输入控件的名称定义为标准的查询字符串属性:

foo=bar&bar=foo&and=soon

That kind of string is easy accesible in almost every "backend" programming language.

这种字符串在几乎所有“后端”编程语言中都很容易访问。

If you need to serialize object information, use JSON.

如果需要序列化对象信息,请使用JSON.

var obj = {
    foo:  'bar',
    more: 'etc
};

serialize this with window.JSON.stringify(obj);. To unserialize such a JSON string, use window.JSON.parse(str);, which returns a javascript object.

window.JSON.stringify(obj);. 要反序列化这样的 JSON 字符串,请使用window.JSON.parse(str);,它返回一个 javascript 对象。

Many languages support this principle.

许多语言都支持这一原则。

回答by nillls

All elements in the form will be sent along if using the $('form').serialize();

如果使用 $('form').serialize();

回答by Danilo Carta

If you want unserialize you must create a function like this;

如果你想反序列化,你必须创建一个这样的函数;

function unserialize(data) {
    data = data.split('&');
    var response = {};
    for (var k in data){
        var newData = data[k].split('=');
        response[newData[0]] = newData[1];
    }
    return response;
}

this function inverse serialize() and return a json data.

此函数反转 serialize() 并返回一个 json 数据。