2015-06-23 35 views
5

我正在處理一個AJAX腳本,它對一個縮短的URL發出GET請求,就像一個bit.ly鏈接。我如何才能真正獲得最終/重定向頁面的URL?如何獲得Ajax重定向後的最終URL?

我可以從重定向的頁面響應報頭,但它似乎並沒有包含網址信息:

$.ajax({ 
    url: "http://www.thislinkredirects.com", 
    success: function(data, status, xhr) { 
    var response = $(data); 
    }, 
    complete: function(xhr) { 
    console.log(xhr.getAllResponseHeaders()); 
    } 
}); 

結果:

Date: Tue, 23 Jun 2015 03:22:07 GMT 
Allow: POST, GET, OPTIONS, PUT, DELETE 
Server: lighttpd/1.4.35 
X-Powered-By: PHP/5.3.3 
Transfer-Encoding: chunked 
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE 
Content-type: text/html 
Access-Control-Allow-Origin: * 
Access-Control-Allow-Headers: accept, authorization 

我沒有控制服務器發出獲取請求。

+0

您是否找到任何解決方案? –

+0

唯一對我有用的是對此網站http://www.wheregoes.com/retracer.php進行AJAX調用,並人工提交表單以獲取URL的最終位置。這是一個巨大的解決方法,但它的工作原理。 –

回答

0

嘗試將jqXHR傳遞給ajaxComplete,然後讀取頭文件。

標題應該顯示一個Location:字段。

+0

這就是我目前正在做的,但到目前爲止,我測試的大多數重定向鏈接都沒有「位置」字段。 –

+0

看看你是否能夠通過嘗試僅使用以下內容來提取該位置:'xhr.getResponseHeader('Location')' – kRiZ

+1

這樣做會返回null。 –

0

試試這個代碼.....

$.ajax({ 
    url: "https://instagram.com/oauth/authorize/?client_id=e40f15a90**c89851d8a66&redirect_uri=http://examle.com&response_type=token", 
    success:function(result,status,xhr){ 
    console.log(xhr.getResponseHeader('Location'));<---NULL 
    } 
}); 
1

正如我回答了類似的問題在這裏:https://stackoverflow.com/a/48445360/1398908

一個更好的解決方案是用這樣的自定義XHR對象提供的jQuery的Ajax:

var xhr = new XMLHttpRequest(); 

$.ajax({ 
    url: '/url', 
    type: 'post', 
    data: '...', 
    xhr: function() { 
     return xhr; 
    } 
}); 

然後你就可以在任何回調訪問當前URL

success: function() { 
    console.log(xhr.responseURL); 
} 
相關問題