我正在尝试从我的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();
})
})
但我在控制台中没有得到任何东西(虽然请求成功执行)。我还注意到更新脚本第二行的输出也没有出现在控制台中。
答案 0 :(得分: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);
})
答案 1 :(得分: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();
})