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
jQuery serialize an object?
提问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.stringify
instead.
使用 vanilla JS,您将JSON.stringify
改为使用。
回答by Sinetheta
回答by Tharabas
You could use JSON.stringify
to 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"}"