gpt4 book ai didi

javascript - 尽管 JSON 有效并且返回代码为 201,jQuery Ajax 返回 "parsererror"

转载 作者:行者123 更新时间:2023-12-01 07:09:03 25 4
gpt4 key购买 nike

我正在向服务器发送查询并等待 JSON 对象返回:

var a = $.ajax(
{
type: "POST",
data: post_data,
timeout: 5000,
url: url,
beforeSend: function (xhr)
{
xhr.setRequestHeader("Content-Type", "application/json");
}
})
.success (function (data, status, jqxhr)
{
onSuccess();
})
.error (function(x, status, jqxhr)
{
onError_(x);
});

效果很好,我得到了预期的 JSON 返回:

{"readyState":4,"responseText":"","status":201,"statusText":"Created"}

但不是 onSuccess() 而是 onError_() 被调用,并且 status 设置为 'parsererror'尽管返回的是有效的 JSON(我已经使用 this 等各种工具对其进行了测试),甚至 JSON 元素的状态是 201 ,根据 this页面代表一个肯定的状态代码:

10.2.2 201 Created

The request has been fulfilled and resulted in a new resource being created [...]

jQuery 的 Ajax 有可能将 201 状态解释为失败吗?

更新:

还将 dataType: "json", 添加到我的请求中并不会改变这种情况。 .ajax() 的 jQuery 文档说

dataType (default: Intelligent Guess (xml, json, script, or html))

因此,当我实现它时,我认为 jQuery 不会那么愚蠢地导致错误,因为它无法识别 JSON,而且看来我是对的,因为错误仍然相同。

更新:

此问题的常见解决方案似乎是在 ajax 调用中添加 dataType: "json" ,但这对我来说不起作用,所以我做了一个丑陋但有效的解决方法:

.error (function(x, status, jqxhr) 
{
if (x.status == 201) /* jQuery thinks, Status 201 means error, but it doesnt so we have to work around it here */
{
// handle success
return;
}

// handle errors
}

无论如何,我仍然对正确的修复感兴趣

最佳答案

请注意:ResponseText 等于“”,这不是有效的 json。它应该为 null 或“{}”

关于javascript - 尽管 JSON 有效并且返回代码为 201,jQuery Ajax 返回 "parsererror",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32350478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com