【问题标题】:The jqXHR object returned by the ajax callajax调用返回的jqXHR对象
【发布时间】:2019-07-25 11:16:03
【问题描述】:

无论是成功事件还是错误事件都会得到返回的jqXHR对象,但是我只能在错误事件中访问jqXHR对象。

    $.ajax({
       type: 'POST',
       url:'https://fakeurl',
       data: formData,
       contentType: 'application/x-www-form-urlencoded',                     
       dataType: 'json',
       success: function(textStatus, jqXHR) {
           alert('textStatus: ' + textStatus + ' jqXHR.status: ' + jqXHR.status);
     },error: function(jqXHR) {
       console.log('jqXHR.status: ' + jqXHR.status);
     }
   });

错误事件中的输出得到 jqXHR.status: 0。 成功事件的输出是 textStatus: [object Object] jqXHR.status: undefined.

【问题讨论】:

  • textStatus 将是 dataType:'json'。那是你的问题。

标签: javascript jquery ajax


【解决方案1】:

来自 jQuery ajax docs:

成功

类型:函数(任何数据,字符串 textStatus,jqXHR jqXHR) ...

所以,如果你想在success 回调中访问jqXHR 对象,你需要定义三个参数让函数接受,如下所示:

success: function(data, textStatus, jqXHR) {
           alert('data: ' + data + 'textStatus: ' + textStatus + ' jqXHR.status: ' + jqXHR.status);

【讨论】:

  • 然后我才意识到我不知道如何正确实现功能......谢谢!
【解决方案2】:

如果要取回提交的数据,success函数的第一个参数是提交的数据,第二个是textStatus,第三个是jqXHR,它具有响应对象的所有属性

$.ajax({
   type: 'POST',
   url:'https://fakeURL',
   data: formData,
   contentType: 'application/x-www-form-urlencoded',
   dataType: 'json',
   success: function(data, textStatus, jqXHR) {
      alert('textStatus: ' + textStatus + ' jqXHR: ' + jqXHR.status);
 },error: function(error) {
   console.log('error.status: ' + error.status);
 }
});

【讨论】:

  • 这是错误的。正如 ajax 文档中所说: success Type: Function( Anything data, String textStatus, jqXHR jqXHR ) 如果请求成功则调用的函数。该函数获得三个参数: 从服务器返回的数据,根据 dataType 参数或 dataFilter 回调函数(如果指定)进行格式化;描述状态的字符串;和 jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象。
猜你喜欢
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
相关资源
最近更新 更多