Javascript jQuery Ajax - 如何获取错误的响应数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9066790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Ajax - how to get response data in error
提问by Roy Tsabari
I have a simple web application. I've created the server REST API so it will return a response with HTTP code and a JSON (or XML) object with more details: application code (specific to scenario, message that describe what happened etc.).
我有一个简单的网络应用程序。我已经创建了服务器 REST API,因此它将返回一个带有 HTTP 代码的响应和一个包含更多详细信息的 JSON(或 XML)对象:应用程序代码(特定于场景、描述发生了什么的消息等)。
So, for example if a client send a Register request and the password is too short, the response HTTP code will be 400 (Bad Request), and the response data will be: {appCode : 1020 , message : "Password is too short"}
.
因此,例如,如果客户端发送 Register 请求并且密码太短,则响应 HTTP 代码将为 400(Bad Request),响应数据将为:{appCode : 1020 , message : "Password is too short"}
。
In jQuery I'm using the "ajax" function to create a POST request. When the server returns something different from HTTP code 200 (OK), jQuery defines it as "error".
在 jQuery 中,我使用“ajax”函数来创建 POST 请求。当服务器返回与 HTTP 代码 200 (OK) 不同的内容时,jQuery 将其定义为“错误”。
The error handler can get 3 parameters: jqXHR, textStatus, errorThrown. Ho can I get the JSON object that sent by the server in error case?
错误处理程序可以获取 3 个参数:jqXHR、textStatus、errorThrown。我可以在错误情况下获取服务器发送的JSON对象吗?
Edit:
编辑:
1) Here is my JS code:
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) When looking at Firebug console, it seems like the response is empty. When invoking the same request by using REST testing tool, I get a response with JSON object it it.
2) 查看 Firebug 控制台时,似乎响应为空。当使用 REST 测试工具调用相同的请求时,我得到一个带有 JSON 对象的响应。
What am I doing wrong?
我究竟做错了什么?
采纳答案by Roy Tsabari
After spending so much time on this problem, I found the problem.
在这个问题上花了这么多时间后,我发现了问题。
The page is under the URL: www.mydomain.com/register
The REST api is under the URL: server.mydomain.com/rest
该页面在 URL 下:www.mydomain.com/register
REST api 在 URL 下:server.mydomain.com/rest
Seems like this kind of POST is not so simple.
I'm going to search more information to understand this issue better (if you have more information please share it with me).
好像这种 POST 没那么简单。
我将搜索更多信息以更好地理解这个问题(如果您有更多信息,请与我分享)。
When putting the REST API under www.mydomain.com/rest - everything is working fine.
将 REST API 放在 www.mydomain.com/rest 下时 - 一切正常。
回答by mpen
Here's an example of how you get JSON data on error:
以下是如何在出错时获取 JSON 数据的示例:
$.ajax({
url: '/path/to/script.php',
data: {'my':'data'},
type: 'POST'
}).fail(function($xhr) {
var data = $xhr.responseJSON;
console.log(data);
});
From 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.
如果指定了 json,则响应在作为对象传递给成功处理程序之前使用 jQuery.parseJSON 进行解析。解析的 JSON 对象通过 jqXHR 对象的 responseJSON 属性可用。
Otherwise, if responseJSON
is not available, you can try $.parseJSON($xhr.responseText)
.
否则,如果responseJSON
不可用,您可以尝试$.parseJSON($xhr.responseText)
。
回答by hvgotcodes
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader()
从 jQuery 1.5 开始,$.ajax() 返回的 jQuery XMLHttpRequest (jqXHR) 对象是浏览器原生 XMLHttpRequest 对象的超集。例如,它包含 responseText 和 responseXML 属性,以及一个 getResponseHeader()
so use the jqXRH argument and get the responseText
property off it.
所以使用 jqXRH 参数并responseText
从它获取属性。
In the link above, look for the section entitled
在上面的链接中,查找标题为
The jqXHR Object
jqXHR 对象
回答by Archit Sanghvi
I also faced same problem when i was using multipart/form-data. At first I thought multipart/form-data created this mess, but later i found the proper solution.
当我使用 multipart/form-data 时,我也遇到了同样的问题。起初我认为 multipart/form-data 造成了这个混乱,但后来我找到了正确的解决方案。
1) JS code before:
1)之前的JS代码:
var jersey_url = "http://localhost:8098/final/rest/addItem/upload";
var ans = $.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jersey_url,
data: formData,
dataType: "json",
processData: false,
contentType: false
success : funtion(data){
var temp = JSON.parse(data);
console.log("SUCCESS : ", temp.message);
}
error : funtion($xhr,textStatus,errorThrown){
console.log("ERROR : ", errorThrown);
console.log("ERROR : ", $xhr);
console.log("ERROR : ", textStatus);
}
});
Here when error occurred, it showed me this in console :-
Error :
Error : { abort : f(e), always : f(), .... , responseJSON :"{"message":"failed"}" }
Error : error
Thus i came to know that we have to use $xhr.responseJSONto get the string message which we sent from rest api.
在这里发生错误时,它在控制台中向我显示了这一点:-
错误:
错误:{中止:f(e),始终:f(),....,responseJSON:“{“消息”:“失败”}“}
错误:错误
因此我知道我们必须使用$xhr.responseJSON来获取我们从 rest api 发送的字符串消息。
2) modified/working error funtion:
2)修改/工作错误功能:
error : funtion($xhr,textStatus,errorThrown){
var string= $xhr.responseJSON;
var json_object= JSON.parse(string);
console.log("ERROR : ", json_object.message);
}
Thus will output "Error : failed"on console.
因此将在控制台上输出“错误:失败”。