HTTP 请求的 JSON 响应正文在服务器端被扭曲。它有一个键,其元素是一个数组。这是我使用 jQuery ajax 的 HTTP 请求:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
当我将 JSON.stringify(event_arr) 打印到控制台时,如下所示:
{"results": [{"event_client": "name1","event_date": "date1"}, {"event_client": "name2", "event_date": "date2"}]}
然后,在服务器端,以下是我理解响应正文并使用 JSON 格式的各种尝试:
// returns [object, Object], cannot be passed into JSON.parse
console.log(request.body);
var temp = JSON.stringify(request.body);
var temp2 = JSON.parse(temp);
// prints {"{\"results\":":{"{\"event_name\":\"name1\",\"event_date\":\"date1\"},{\"event_name\":\"name2\",\"event_date\":\"date2\"}":""}}
console.log(temp);
// prints { '{"results":': { '{"event_name":"name1","event_date":"date1"},{"event_name":"name2","event_date":"date2"}': '' } }
console.log(temp2);
在我的 dbInsert() 中调用的 JSON.stringify() 似乎搞乱了 JSON 的读取方式,而且我不知道如何解决这个内部格式错误!
最佳答案
您需要在 $.ajax({})
函数中设置:contentType: "application/json"
。
类似这样的事情:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
contentType: "application/json",
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
}
关于javascript - Ajax HTTP 请求使用请求正文中的数组更改 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45619197/