2017-05-22 120 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(); 

})