如何从jQuery获取响应头位置?

rae*_*aeq 17 javascript ajax jquery response

所以我试图通过jQuery get从头响应中获取位置.我尝试使用getResponseHeader('Location')和getAllResponseHeaders(),但它们似乎都返回null.

这是我目前的代码

$(document).ready(function(){
   var geturl;
   geturl = $.ajax({
      type: "GET",
      url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
   });
   var locationResponse = geturl.getResponseHeader('Location');
   console.log(locationResponse);
});
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 33

异步请求返回时,标头将可用,因此您需要在成功回调中读取它们:

$.ajax({
    type: "GET",
    url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
    success: function(data, status, xhr) {
        console.log(xhr.getResponseHeader('Location'));
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @raeq这帮助了我:http://stackoverflow.com/questions/5822985/cross-domain-resource-sharing-get-refused-to-get-unsafe-header-etag-from-re (6认同)
  • 尝试`complete:function(xhr){console.log(xhr.getAllResponseHeaders()); }` (3认同)
  • 你得到的错误可能是因为同源政策. (3认同)

小智 6

jQuery 将 XMLHttpRequest 对象抽象为一个所谓的“超级集”,它不公开 responseURL 字段。在他们的文档中,他们讨论了“jQuery XMLHttpRequest (jqXHR) 对象”

For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

readyState
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
status
statusText
abort( [ statusText ] )
getAllResponseHeaders() as a string
getResponseHeader( name )
overrideMimeType( mimeType )
setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
statusCode( callbacksByStatusCode )
No onreadystatechange mechanism is provided, however, since done, fail, always, and statusCode cover all conceivable requirements.
Run Code Online (Sandbox Code Playgroud)

如您所见,无法获取响应 URL,因为 jqXHR API 没有公开它

  • jQuery 似乎是页面上唯一具有任何形式正确性的答案,它既不公开 responseUrl,也不在响应标头中提供 Location。 (2认同)

uin*_*tea 5

对于jQuery Ajax中的一些头文件,您需要访问XMLHttpRequest对象

var xhr;
var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
  xhr = _orgAjax();
  return xhr;
};

$.ajax({
    type: "GET",
    url: 'http://example.com/redirect',
    success: function(data) {
        console.log(xhr.responseURL);
    }
});
Run Code Online (Sandbox Code Playgroud)

或使用普通的JavaScript

var xhr = new XMLHttpRequest();
xhr.open('GET', "http://example.com/redirect", true);

xhr.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    console.log(xhr.responseURL);
  }
};

xhr.send();
Run Code Online (Sandbox Code Playgroud)