2013-05-08 46 views
8

假設我使用ajax(例如通過jQuery)對實現PRG模式的API執行POST請求。因此,它會重定向我:那麼重定向後從XHR對象獲取最終url

POST /some/api 
HTTP/1.1 303 See Other 
Location: /some/other/location 

jQuery將自動執行重定向,執行:

GET /some/other/location 

,然後調用響應處理器(成功,失敗等)與輸出從後者請求。但是,如何在javascript中讀取最終資源的位置(本例中爲/some/other/location)?

+0

根據[本答案](http://stackoverflow.com/a/8056313/759866),它正在最新的瀏覽器中實現。 – Benjamin 2016-06-20 21:49:32

回答

5

據我所知,這是不可能的XMLHttpRequest對象。但是,如果你在你的[信任]域中執行的,如果它是重要的信息,你可以使用,而不是一個iframe:

var hidden_iframe = document.createElement('iframe'); 
hidden_iframe.name = 'hidden_iframe'; 
hidden_iframe.style.display = 'none'; 
hidden_iframe.onload = function() { 
    console.log(hidden_iframe.contentWindow.location.toString()); 
} 
document.body.appendChild(hidden_iframe); 

var request = document.createElement('form'); 
request.method = 'post'; 
request.action = '/some/api'; 
request.target = 'hidden_iframe'; 
request.style.display = 'none'; 

// append INPUTs to the request form here 

document.body.appendChild(request); 
request.submit(); 

您的控制檯應該報告1個或多個URL,其中最後將是:

http(s)://{yourdomain}/some/other/location

+0

感謝您的建議。使用框架而不是'XMLHttpRequest'通過事件處理等有點毛病,但在某些情況下可能會有用。 – Jeroen 2013-05-15 18:56:46

4

XMLHttpRequest的不公開的最終URL。

,你可以破解這周圍沒有使用iframe。如果你返回一個JSON對象,你可以添加一個finalURL屬性,如下所示:

{ "finalURL": "http://example.com/API/v2/request.json", "response": {...} } 

和閱讀來獲取重定向後的URL。希望這有幫助!

0

這是一箇舊帖子,但它在Google中排名很高,所以我會添加我的解決方案。

如果您可以控制ajax響應,則可以使用最終的URL向響應添加標題。

在PHP中,這會是這樣的:

header('X-final-url: /some/other/location')

然後,在jQuery的,您可以訪問該值:

var finalUrl = jqXHR.getResponseHeader('X-final-url');

的Symfony添加頁眉與內核聽衆:

服務

app.kernel.response_metadata_populator: 
    class: AppBundle\Listeners\ResponseMetadataPopulator 
    tags: 
     - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse } 

列表ener類

class ResponseMetadataPopulator 
{ 
    /** 
    * @param FilterResponseEvent $event 
    */ 
    public function onKernelResponse(FilterResponseEvent $event) 
    { 
     $response = $event->getResponse(); 
     $response->headers->set('X-FINAL-URL', $event->getRequest()->getRequestUri()); 
    } 
}