2012-08-10 88 views
2

我有一個uri傳遞給我一個休息電話,這是一個重定向url,我希望能夠攔截調用以獲得重定向'位置'的標題。如何攔截並獲取重定向URL的位置標題?

以下代碼對位置標題返回null。執行這個客戶端的正確方法是什麼?

$(document).ready(function() { 
    $.ajax({ 
     url: 'http://myserver.com/redirect?token=AAAnY13Y-76LZ4zXDOd', // obviously not cross domain and contains redirect location to a youtube link to embed in my page, http://www.youtube.com/embed/bl2j345-xy 
     data: { 
      something: 'someotherthing' 
     }, 
     complete: function (request, status) { 
      var location = request.getResponseHeader("Location"); // this is null...it shows up in Fiddler as http://www.myotherserver.com in the Location Header 
     }, 
     error: function (request, error) { 
      alert(request.responseText); 
     } 
    }); 
}); 
+0

[如何在jQuery Ajax調用後管理重定向請求](http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery- ajax-call)還有相關:http://stackoverflow.com/q/282429/995876 – Esailija 2012-08-10 22:29:21

+0

我不確定是否只是爲我而是'status' ='error'。這可能是你沒有迴應標題的原因嗎? – Nope 2012-08-10 22:34:49

+0

@FrançoisWahl:的確如此,我剛查過,狀態是錯誤的。它在工作之前,但絕對錯誤,但request.responseText是空白。 – JaJ 2012-08-10 22:51:36

回答

0

使用此fiddle。我稍微更新了代碼,添加了一些控制檯輸出以進行調試,因爲我目前總是收到錯誤:NETWORK_ERR: XMLHttpRequest Exception 101

我所做的主要更改,我認爲可能是您的空標題的原因,設置爲async: false。這很重要,因爲您不希望請求在完成之前返回。如果未指定,則默認設置爲async: true,這會導致ajax調用立即返回,這可能是爲什麼即使調用成功,您也不會看到響應標頭。

我還添加了一個success: function...回調與一個簡單的調試,以確保它被抓住,如果它在那裏。

在阿賈克斯documentation還檢查了部分在跨域非異步請求和跨域的設置:

async
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

crossDomain(added 1.5)
Default: false for same-domain requests, true for cross-domain requests
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain.

我不知道,如果一個重定向被認爲是跨域但我猜測上述的組合是錯誤和空請求標題的原因。

+0

很酷,謝謝!但是,我做每控制檯登錄得到一個錯誤......有沒有在那裏有很多的錯誤信息: 錯誤,狀態文本:錯誤 完整,狀態:錯誤 完整,狀態文本:錯誤 完整-responseHeaders響應: – JaJ 2012-08-10 23:27:23

+0

@ JaJ:如果在完整和/或錯誤回調的頂部放置一個「調試器」行,腳本將停在那裏,然後您可以使用控制檯查看完整的請求對象,只需在控制檯中鍵入'request'獲取對象。例如,在Chrome中,您可以很好地遍歷整個對象屬性,然後查看您可以在控制檯中調用的方法。 – Nope 2012-08-10 23:51:45

+0

@Jaj:出於好奇,你可以直接從你的電腦在瀏覽器中訪問主要的URL嗎?另外,你是否將這個作爲一個內部網站使用Windows身份驗證來運行?當代碼嘗試訪問url時,可能存在訪問問題?我只想大聲:) – Nope 2012-08-10 23:56:48