jQuery - получить заголовки ответа AJAX

Как мы получаем доступ к заголовкам ответа, когда запускаем ajax-запрос с помощью jQuery? Я попытался использовать приведенный ниже код в соответствии с предложениями, приведенными на некоторых сайтах. Но объект 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');

person Apps    schedule 11.07.2012    source источник


Ответы (2)


Для обратной совместимости с XMLHttpRequest объект jqXHR будет предоставлять следующие свойства и методы: getAllResponseHeaders() и getResponseHeader(). Из документа $.ajax(): http://api.jquery.com/jQuery.ajax/

Для jQuery > 1.3

success: function(res, status, xhr) { 
  alert(xhr.getResponseHeader("myHeader"));
}
person odupont    schedule 12.07.2012
comment
getAllResponseHeaders() дает только content-length: 0 content-type: text/html; charset=UTF-8, но в сети Chrome я вижу Access-Control-Allow-Credentials: fa... ... Access-Control-Allow-Origin: sho... Access-Control-Max-Age: 1728... Connection: keep-alive Content-Length: 0 Content-Security-Policy: frame-ancestors 'none' Content-Type: text/ html; charset=UT Обновление: 0; url=sec... Сервер: nginx/1.1... Set-Cookie: lang=ru; ... узнать больше. Мне нужно обновить, но я не могу его получить - person maxkuku; 18.03.2021

ДЛЯ JQUERY 3 И ПОЗДНЕЕ

Вот решение, которое сработало для меня:

//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'));
  });
}
person sticky_elbows    schedule 20.11.2018