jQuery 序列化一个对象?

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

jQuery serialize an object?

jqueryserialization

提问by Seamus James

Say I have something like:

说我有这样的事情:

var obj = {id: 1, name: "Some name", color: "#444444" };

I want to serialize that object. I tried:

我想序列化那个对象。我试过:

$(obj).serialize();

but that didn't work.

但这没有用。

Any ideas?

有任何想法吗?

回答by Sarfraz

You should use jQuery.param()instead.

你应该jQuery.param()改用。

Working Example

工作示例

With vanilla JS, you would use JSON.stringifyinstead.

使用 vanilla JS,您将JSON.stringify改为使用。

回答by Sinetheta

As mentioned you should use .param()

如前所述,您应该使用 .param()

$.param({id: 1, name: "Some name", color: '#444444' })

But also you need to be careful with your syntax. Your brackets don't match, and that color will need quotation marks. jsFiddle

但你也需要小心你的语法。您的括号不匹配,该颜色需要引号。js小提琴

回答by Tharabas

You could use JSON.stringifyto serialize your object, and you'd have to wrap your color string correctly:

您可以使用JSON.stringify序列化对象,并且必须正确包装颜色字符串:

var obj = {id: 1, name: "Some name", color: '#444444' };
var serialized = JSON.stringify(obj);
// => "{"id":1,"name":"Some name","color":"#444444"}"