我正在尝试向我的网络应用程序提交一些 JSON,我希望 JSON 是这样的:
{
"thing1" :
{
"something" : "hello"
},
"list_of_things" :
[
{
"item1" : "hello"
},
{
"item2" : "hello"
}
]
}
这里我有一个 JSON 对象和一个包含 JSON 对象的 JSON 数组。当我创建要用 Javascript 提交的数据时,我会:
form = {
"thing1" : {
"something" : somethingVariable
},
"list_of_things" : listArray
}
此处“listArray”是 Javascript 哈希对象的 Javascript 数组对象。我使用 jQuery 的 ajax 方法提交这个,但不是将 javascript 数组显示为所需的 JSON 数组,而是将其转换为一系列 JSON 对象,如下所示:
{ "1" : { "thing1" : "something" }, "2" : { "thing2" : "something" }...
如何让数组作为数组提交,而不是转换成一系列以数组索引为键的 JSON 对象?
编辑#1:“listArray”是一个简单的 Javascript 数组,定义如下:
var listArray = new Array();
listArray.push({ "thing1" : "something" });
listArray.push({ "thing2" : "something" });
编辑#2:“表单”通过以下调用发送到服务器:
$.ajax({
type: 'POST',
url: '/url',
dataType: "json",
data: form,
success: function(data) {
/* success code here */
}
});
最佳答案
看看here .如果您真的想发布 JSON,则需要发送字符串,而不是对象文字。您可以在 form
上使用 JSON.stringify
( or a more supported JSON solution )。
$.ajax({
url: "/url",,
dataType: "json",
type: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify(form)
});
关于Javascript 数组转换为 JSON 对象而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6653293/