【问题标题】:How to get Response Header location from jQuery Get?如何从 jQuery Get 获取响应头位置?
【发布时间】:2012-06-28 18:02:12
【问题描述】:

所以我试图通过 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);
});

【问题讨论】:

标签: javascript jquery ajax response


【解决方案1】:

异步 请求返回时,标头将可用,因此您需要在 success callback 中阅读它们:

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

【讨论】:

  • 试过了,但没有成功。 url 没有返回成功声明。我也尝试将其打印为 false 也没有运气
  • 试试complete: function(xhr){ console.log(xhr.getAllResponseHeaders()); }
  • 您遇到的错误可能是由于 Same-Origin-Policy。
  • @raeq 这对我有帮助:stackoverflow.com/questions/5822985/…
  • 只有在响应状态为 200 时才调用成功方法,但在这种情况下我认为是 302
【解决方案2】:

对于 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);
    }
});

或使用纯 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();

【讨论】:

【解决方案3】:

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.

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

【讨论】:

  • 看似页面上唯一具有任何形式正确性的答案,jQuery 既不公开 responseUrl,也不在响应标头中提供 Location。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2020-01-02
  • 2020-08-10
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多