【发布时间】:2016-12-16 18:21:15
【问题描述】:
我在一个使用 jQuery 的 Web 应用程序中工作,我对 JSON 格式感到困惑。对于服务器,我使用的是restful Json Server。
问题是不知道是什么问题。错误是我发布到服务器的 Json 格式(使用 Ajax 的 HTTP POST)似乎不正确。我将尝试逐步解释这一点。
Json Server(http://localhost:3000/db)的初始情况是:
{
"userRecipes": []
}
现在,我创建一个 Json 对象如下:
var example2json = {
"description":"some desc",
"trigger":{
"triggerType":"exampleType",
"field1":"something1",
"field2":"something2",
"field3":"something3"
}
};
然后将这个虚构的对象发送 3 次到服务器:
$.ajax({
method: "post",
url: "http://localhost:3000/userRecipes",
data: example2json,
dataType: "json",
success: function(response) {
$('#recipedDescriptionModal').modal('hide');
url = "#SuccessRepice";
window.location.replace(url);
}
});
此后Json服务器状态结果为:
{
"userRecipes": [
{
"description": "some desc",
"trigger[triggerType]": "exampleType",
"trigger[field1]": "something1",
"trigger[field2]": "something2",
"trigger[field3]": "something3",
"id": 1
},
{
"description": "some desc",
"trigger[triggerType]": "exampleType",
"trigger[field1]": "something1",
"trigger[field2]": "something2",
"trigger[field3]": "something3",
"id": 2
},
{
"description": "some desc",
"trigger[triggerType]": "exampleType",
"trigger[field1]": "something1",
"trigger[field2]": "something2",
"trigger[field3]": "something3",
"id": 3
}
]
}
为什么 Json 格式会发生变化?当我想访问一个字段时,我必须这样做:
console.log(JSON.stringify(response.data.userRecipes[1]["trigger[triggerType]"]));
但我会这样做:
console.log(JSON.stringify(response.data.userRecipes[1].trigger.triggerType));
我肯定会在某个地方出错,但不知道在哪里。
我唯一的怀疑是我错误地创建了 Json(一些嵌套在数组元素中的对象)或者我不知道这个 Json 服务器的某些内容。
【问题讨论】:
-
我也尝试在 AJAX POST 上使用
data: JSON.stringify(example2json),但在 Json Server 中我从字面上看到:{ "{\"description\":\"some desc\",\"trigger\":{\"triggerType\":\"exampleType\",\"field1\":\"something1\",\"field2\":\"something2\",\"field3\":\"something3\"}}": "", "id": 4 }。
标签: jquery json nested json-server