2012-06-27 35 views
16

所以我想通過jQuery獲取頭部響應的位置。我嘗試使用getResponseHeader('Location')和getAllResponseHeaders(),但他們似乎都返回null。如何從jQuery獲取響應頭位置?

這裏是我當前的代碼

$(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); 
}); 
+0

可能重複的http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call –

回答

25

的標題將可當異步要求退貨,所以你需要在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')); 
    } 
}); 
+1

試圖沒有運氣。該網址沒有返回成功聲明。我嘗試將它打印出來,但也沒有運氣 – raeq

+3

嘗試使用'complete:function(xhr){console.log(xhr.getAllResponseHeaders()); }' – Bergi

+3

我仍然得到一個空或空字符串http://jsfiddle.net/nNwGL/1/ – raeq

3

一些報頭您需要訪問XMLHttpRequest對象的jQuery Ajax

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(); 
-1

jQuery的抽象在所謂的「超集」不暴露responseURL字段XMLHttpRequest對象。這是在他們的文檔,他們談「的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不公開它