Ajax HTTP 请求更改 JSON 请求正文中包含数组

Ajax HTTP request changes JSON with array in request body

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);
    }
  });
}