jQuery 获取 AJAX 响应正文以用于错误回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2084484/
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
Getting AJAX response body for use in error callback
提问by Tom Lehman
jQuery's AJAX error function has the following parameters:
jQuery 的 AJAX 错误函数有以下参数:
error(XMLHttpRequest, textStatus, errorThrown)
What's the best cross-browser way to get the response body?
获取响应正文的最佳跨浏览器方式是什么?
Does this work (reliably in all browsers)?
这是否有效(在所有浏览器中可靠)?
$.ajax({
error: function(http) {
alert(http.responseText);
}
});
采纳答案by Emil Ivanov
There is a hidden function that can extract the data from XHR istance:
有一个隐藏函数可以从 XHR 实例中提取数据:
var responseText = $.httpData(xhr)
If you pass "json"
as a second parameter it will treat the response as a JSON string.
如果您"json"
作为第二个参数传递,它会将响应视为 JSON 字符串。
Note that you might get an error because there is no response (network problem for example). Make sure you cover that case as well. Also, I believe (not sure) that jQuery invokes the error
handler if the server returns a 4xx
or 5xx
status.
请注意,由于没有响应(例如网络问题),您可能会收到错误消息。确保你也涵盖了这种情况。另外,我相信(不确定)error
如果服务器返回 a4xx
或5xx
状态,jQuery 会调用处理程序。
回答by dowski
As of jQuery 1.4.1 you should use:
从 jQuery 1.4.1 开始,您应该使用:
var json = JSON.parse(xhr.responseText);
回答by Pierre de LESPINAY
For a more recent and general answer (since jquery 1.5), I'd use the jqXHR
object:
对于更新和通用的答案(自 jquery 1.5 起),我将使用该jqXHR
对象:
$.ajax(url).fail(function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
})
Alternatively responseJSON
can be used to get the response body already parsed
或者responseJSON
可用于获取已解析的响应正文
$.ajax(url).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseJSON);
})
回答by Vlado
One straightforward usage example with jQuery:
jQuery 的一个简单用法示例:
var url = '/';
$.get(url).then(
function(response) {
$("#result").html(response);
},
function(jqXHR) {
$("#result").html('Error occurred: '+ jqXHR.statusText + ' ' + jqXHR.status);
}
);
This should return the HTML of current website front page.
这应该返回当前网站首页的 HTML。
Then try entering a nonsense URL that doesn't exist and see the error thrown. You should get "404 Not Found" from web server. Test it: JSFiddle here
然后尝试输入一个不存在的无意义 URL 并查看抛出的错误。您应该从 Web 服务器获得“404 Not Found”。测试一下:JSFiddle在这里