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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:44:04  来源:igfitidea点击:

Getting AJAX response body for use in error callback

jqueryajax

提问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 errorhandler if the server returns a 4xxor 5xxstatus.

请注意,由于没有响应(例如网络问题),您可能会收到错误消息。确保你也涵盖了这种情况。另外,我相信(不确定)error如果服务器返回 a4xx5xx状态,jQuery 会调用处理程序。

回答by dowski

As of jQuery 1.4.1 you should use:

从 jQuery 1.4.1 开始,您应该使用:

var json = JSON.parse(xhr.responseText);

See http://api.jquery.com/jQuery.parseJSON/.

请参阅http://api.jquery.com/jQuery.parseJSON/

回答by Pierre de LESPINAY

For a more recent and general answer (since jquery 1.5), I'd use the jqXHRobject:

对于更新和通用的答案(自 jquery 1.5 起),我将使用该jqXHR对象:

$.ajax(url).fail(function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.responseText);
})

Alternatively responseJSONcan 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在这里