gpt4 book ai didi

javascript - jQuery Ajax - 如何错误地获取响应数据

转载 作者:IT王子 更新时间:2023-10-29 02:59:46 26 4
gpt4 key购买 nike

我有一个简单的网络应用程序。我已经创建了服务器 REST API,因此它将返回包含 HTTP 代码和 JSON(或 XML)对象的响应,其中包含更多详细信息:应用程序代码(特定于场景、描述所发生情况的消息等)。

因此,例如,如果客户端发送注册请求并且密码太短,则响应 HTTP 代码将为 400(错误请求),响应数据将为:{appCode : 1020 , message : “密码太短”

在 jQuery 中,我使用“ajax”函数来创建 POST 请求。当服务器返回不同于 HTTP 代码 200 (OK) 的内容时,jQuery 将其定义为“错误”。

错误处理器可以获得3个参数:jqXHR、textStatus、errorThrown。如何获取服务器错误情况下发送的JSON对象?

编辑:

1) 这是我的 JS 代码:

function register (userName, password) {
var postData = {};
postData["userName"] = userName;
postData["password"] = password;

$.ajax ({
dataType: "json",
type: "POST",
url: "<server>/rest/register",
data: postData,
success: function(data) {
showResultSucceed(data);
hideWaitingDone();
},
error: function (jqXHR, textStatus, errorThrown) {

showResultFailed(jqXHR.responseText);
hideWaitingFail();
}
})
}

2) 查看 Firebug 控制台时,响应似乎是空的。当使用 REST 测试工具调用相同的请求时,我收到了一个带有 JSON 对象的响应。

我做错了什么?

最佳答案

下面是一个如何获取错误 JSON 数据的示例:

$.ajax({
url: '/path/to/script.php',
data: {'my':'data'},
type: 'POST'
}).fail(function($xhr) {
var data = $xhr.responseJSON;
console.log(data);
});

来自 the docs :

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

否则,如果 responseJSON 不可用,您可以尝试 $.parseJSON($xhr.responseText)

关于javascript - jQuery Ajax - 如何错误地获取响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066790/

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