簡體   English   中英

ajax調用返回的jqXHR對象

[英]The jqXHR object returned by the ajax call

成功事件或錯誤事件都會得到返回的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。

來自 jQuery ajax文檔

成功

類型:函數(任何數據,字符串 textStatus,jqXHR jqXHR) ...

所以,如果你想在success回調中訪問jqXHR對象,你需要定義三個參數讓函數接受,如下所示:

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

如果要取回提交的數據,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);
 }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM