我需要将一个对象序列化为JSON。我用的是jQuery。是否有一个“标准”的方法来做到这一点?
我的具体情况:我有一个数组定义如下所示:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
我需要把它变成一个字符串传递给$.ajax()像这样:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
上面的解决方案没有考虑到的一件事是,如果您有一个输入数组,但只提供了一个值。
例如,如果后端期望一个People数组,但在这个特定的情况下,您只是在处理一个人。然后做:
<input type="hidden" name="People" value="Joe" />
然后用之前的解,它会映射到像这样的东西:
{
"People" : "Joe"
}
但是它应该映射到
{
"People" : [ "Joe" ]
}
为了解决这个问题,输入应该是这样的:
<input type="hidden" name="People[]" value="Joe" />
您将使用以下函数(基于其他解决方案,但进行了一些扩展)
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (this.name.substr(-2) == "[]"){
this.name = this.name.substr(0, this.name.length - 2);
o[this.name] = [];
}
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};