jQuery - 获取 AJAX 响应头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11440918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - get AJAX response headers
提问by Apps
How do we get access to the response headers when we fire an ajax request using jQuery? I tried with the below code as per the suggestions given in some sites. But xhr
object is coming as null. I see an xhr
object in this context. But it doesn't have methods to access response headers.
当我们使用 jQuery 触发 ajax 请求时,我们如何访问响应头?我根据某些站点中给出的建议尝试使用以下代码。但是xhr
对象是空的。我xhr
在这种情况下看到了一个对象。但它没有访问响应头的方法。
function SampleMethod(){
var savedThis=this;
this.invokeProcedure=function(procedurePath){
$.ajax({
type: "GET",
url: procedurePath,
dataType: "json",
success: function(data,status,xhr){savedThis.resultSetHandler(data,status,xhr);}
});
}
this.resultSetHandler=function(data,status,xhrObj){
//Handle the result
}
this.errorHandler=function(args){
//Handle the result
}
}
var sampleObj=new SampleMethod();
sampleObj.invokeProcedure('url');
回答by odupont
For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods: getAllResponseHeaders()and getResponseHeader(). From the $.ajax() doc : http://api.jquery.com/jQuery.ajax/
为了与 XMLHttpRequest 向后兼容,jqXHR 对象将公开以下属性和方法:getAllResponseHeaders()和 getResponseHeader()。来自 $.ajax() 文档:http: //api.jquery.com/jQuery.ajax/
For jQuery > 1.3
对于 jQuery > 1.3
success: function(res, status, xhr) {
alert(xhr.getResponseHeader("myHeader"));
}
回答by sticky_elbows
UPDATE 2018 FOR JQUERY 3 AND LATER
JQUERY 3 及更高版本的 2018 年更新
I know this is an old question but hopefully this solution will help those who couldn't find a solution. Here is the solution that worked for me:
我知道这是一个老问题,但希望这个解决方案能帮助那些找不到解决方案的人。这是对我有用的解决方案:
//I only created this function as I am making many ajax calls with different urls and appending the result to different divs
function makeAjaxCall(requestType, urlTo, resultAreaId){
var jqxhr = $.ajax({
type: requestType,
url: urlTo
});
//this section is executed when the server responds with no error
jqxhr.done(function(){
});
//this section is executed when the server responds with error
jqxhr.fail(function(){
})
//this section is always executed
jqxhr.always(function(){
//here is how to access the response header
console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
});
}