簡體   English   中英

AJAX請求-獲取成功請求的HTTP代碼/響應頭

[英]AJAX Request - get HTTP Code/Response Header for successful request

我正在嘗試從我的AJAX請求中獲取HTTP響應代碼/響應頭。 這是我的原始腳本:

 $("#callContact1").click(function() { $.ajax({ url: "https://www.server.com?type=makecall", data: {}, type: "GET" }) .then(function(data) { $('#ajaxResponse').html(data).show(); }) .fail(function(xhr) { var httpStatus = (xhr.status); var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus; console.log('ajaxError: ' + ajaxError); //make alert visible $('#ajaxResponse').html(ajaxError).show(); }) }) 

工作正常。 我已經對此進行了更新,以嘗試獲取HTTP響應代碼/標頭並在console.log中查看此信息,但在那里什么都看不到。 這是我更新的腳本:

 $("#callContact1").click(function() { console.log('starting call back request'); $.ajax({ url: "https://www.server.com?type=makecall", data: {}, type: "GET" }) .then(function(data) { $('#ajaxResponse').html(data).show(); var httpStatus = (data.status); var httpResponseCode = (data.getAllResponseHeaders); console.log('httpStatus: ' + httpStatus); console.log('httpResponseCode: ' + httpResponseCode); }) .fail(function(xhr) { var httpStatus = (xhr.status); var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus; console.log('ajaxError: ' + ajaxError); //make alert visible $('#ajaxResponse').html(ajaxError).show(); }) }) 

但我在控制台中什么都沒得到(盡管請求已成功執行)。 我還注意到更新的腳本第二行的輸出也未出現在控制台中。

修改上面的代碼為

.then(function(data,status,xhr) {
      $('#ajaxResponse').html(data).show();
      var httpStatus = status;
      var httpResponseCode = (xhr.status);
      console.log('httpStatus: ' + httpStatus);
      console.log('httpResponseCode: ' + httpResponseCode);
    })

您可以在jQuery的jQuery.ajax()文檔中找到

https://api.jquery.com/jQuery.ajax#jqXHR

可以使用.done()和.fail()或使用。然后() ,其既包含,使用兩個回調函數作為參數,所述第一成功,第二個用於FAIL。

因此,您可以像這樣使用smt:

.then(function(data, status, xhr) {
    $('#ajaxResponse').html(data).show();
    var httpStatus = status;
    var httpResponseCode = (xhr.status);
    console.log('httpStatus: ' + httpStatus);
    console.log('httpResponseCode: ' + httpResponseCode);
}, function(data, status, xhr) {
    var ajaxError = 'There was an requesting the call back. HTTP Status: ' + status;
    console.log('ajaxError: ' + ajaxError); //make alert visible 
    $('#ajaxResponse').html(ajaxError).show();

})

暫無
暫無

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

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