2017-05-22 175 views
1

我想從我的AJAX請求獲取HTTP響應代碼/響應頭。這裏是我的原創劇本: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(); 
 
    }) 
 
})

但我不會在控制檯中得到任何東西(請求成功運行雖然)。我也注意到更新腳本的第二行輸出也沒有出現在控制檯中。

+1

清除瀏覽器歷史記錄,然後嘗試在有關CORS或許控制檯 – JYoThI

+0

什麼?或Access-Control- *標題? –

+0

我重新啓動瀏覽器,我現在看到控制檯中的條目,但我得到「undefined」值而不是預期值: httpStatus:undefined httpResponseCode:undefined – user982124

回答

2

修改上面的代碼

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

正如你可以jQuery的文檔中找到jQuery.ajax()

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

你可以使用.done()和.fail()或者使用.then(),它包含兩個參數,使用兩個回調函數作爲參數,第一個用於成功,第二個用於失敗。

所以,你可以使用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(); 

})