2011-04-02 80 views
7

我有一個菜單,其中包含一些鏈接,用於更新div content並在加載後執行功能onSuccess如何在ajax請求後更改URL?

<li>@Ajax.ActionLink("Home", "Index", "home")</li> 
<li>@Ajax.ActionLink("Download", "Index", "download")</li> 

如果我在網址/home上並點擊下載鏈接,則div更改成功。問題是URL沒有改變。

如何檢索請求的URL,以便在成功請求時撥打history.pushState

回答

6

this question (How to get request url in a jQuery $.get/ajax request)我發現我可以用this.url檢索它。

MDC window.history我發現的語法和MDC Manipulating the browser history我發現我可以得到history.state當前狀態(似乎並不雖然在Chrome瀏覽器),並發現,調用pushState時,我只能在stateObject發送640K字否則會拋出異常。

我現在成功的Ajax請求的方法是:

OnSuccess: function(html, status, xhr){ 
    var requestedUrl = this.url.replace(/[&?]X-Requested-With=XMLHttpRequest/i, ""); 

    // if the url is the same, replace the state 
    if (window.location.href == requestedUrl) 
    { 
     history.replaceState({html:html}, document.title, requestedUrl); 
    } 
    else 
    { 
     history.pushState({html:html}, document.title, requestedUrl); 
    } 
}, 

對於基本的測試,我存儲在stateObject全部結果,如果它拋出一個例外,我將設置URL反而能夠使一個新的請求。

popstate事件是

$(window).bind("popstate", function (e) { 
    var state = e.originalEvent.state; 
    $("#body").html(state.html); 
}); 

它恢復的頁面,因爲它是以前,我並不需要作出新的請求。

2

我能想到實現這一點的唯一方法是使用jQuery來處理鏈接的點擊事件。所以你可以添加一個class屬性到你的鏈接如下;

@Ajax.ActionLink("Home", "Index", "home", new { @class = "menuLinks" }) 

添加您的點擊事件;

$(".menuLinks").click(function() { 
    history.pushState(stateObj, $(this).html, $(this).attr("href")); 
} 

不是很familar與pushState的簽名,但我相信用「A」標記的href將作爲一個有效的URL傳遞給pushState的。