为什么空的 200 在 jQuery 中会导致失败?

Why does an empty 200 create a fail in jQuery?

我创建了一个简单的 ajax 请求 post 一些 json 到我的 api。我以前在其他页面上做过几次,但突然间我无法让这个新调用正常工作。

var request = $.ajax({
    type: "POST",
    url: "/my-api-call",
    dataType: "json",
    data: JSON.stringify({"pid": 5, "comment": $('#comment').val()})
});
request.done(function(data){
    console.log('weve got a succesful response!!');
})
request.fail(function(error){
    console.log('weve got an error!!!');
    console.log(error);
});

调用只是 returns 一个空的 200 响应,我在浏览器中对此进行了验证。但不知何故,浏览器控制台不断显示 weve got an error!!!。如您所见,我也记录了错误,但我是一个充满信息的对象,我不知道其中的重要内容。在该错误对象中,它还表示响应是普通的 200 btw。

看到这段代码相当简单,我真的想不出我做错了什么。

有人知道我做错了什么吗?欢迎所有提示!

这是因为您已将 dataType 设置为 json。所以 jquery 正在尝试将您的数据(为空)解析为 json。空结果无效 json.

"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

From the docs

所以你应该 return {}null