【问题标题】:Input JSON is invalid. Request body must be valid JSON if content type is application/json输入 JSON 无效。如果内容类型为 application/json,则请求正文必须是有效的 JSON
【发布时间】:2018-04-21 10:16:11
【问题描述】:

我将以下 JSON object 传递给我的 AJAX 调用

var contact = {
   "accessToken": "xxx-xxx-xxx-xxx-xxx",
   "email": "test@test.com",
   "customFields": {
      "custom7": {"value": "test rep"},
      "custom8": {"value": "test title"},
      "custom9": {"value": "test@localdev.com"}
   }
}

这是我的 AJAX 调用:

$.ajax({
   type: 'POST',
   url: 'https://api.mydomain.com/v1/contacts/save',
   data: contact,
   dataType: 'json',
   success: function(data) {
     alert(data.errors);
   }
});

data.errors 显示如下:

输入 JSON 无效。如果内容,请求正文必须是有效的 JSON 类型是应用程序/json

我用jsonlint.com 检查了上面的 JSON 对象,它得到了验证。 我不明白我在哪里做错了!

【问题讨论】:

    标签: jquery json content-type jquery-ajaxq


    【解决方案1】:

    在传递该 json 之前对其进行字符串化 -

    $.ajax({
        type: 'POST',
        url: 'https://api.mydomain.com/v1/contacts/save',
        data: JSON.stringify(contact),
        dataType: 'json',
        success: function(data) {
            alert(data.errors);
        }
    });
    

    【讨论】:

    • 谢谢!有效。但是,我必须添加 contentType: application/jsondataType: json
    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 2015-04-29
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多