【问题标题】:Ajax HTTP request changes JSON with array in request bodyAjax HTTP 请求使用请求正文中的数组更改 JSON
【发布时间】:2017-08-11 01:19:47
【问题描述】:

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",然后再次检查您在服务器端获得的内容。
  • 这样就行了!非常感谢,这是一个如此简单的修复。

标签: javascript jquery json ajax httpresponse


【解决方案1】:

您需要在$.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);
    }
  });
}

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 2020-10-04
    • 2021-08-14
    • 2011-01-17
    相关资源
    最近更新 更多