开发者

How to change URL after an ajax request?

I have a menu with some links that update the div content and execute the function onSuccess after it is loaded.

<li>@Ajax.ActionLink("Home", "Index", "home")</li>
<li>@Ajax.Action开发者_运维问答Link("Download", "Index", "download")</li>

If I am on the url /home and click the download link the div changes successfully. The problem is that the URL is not changed.

How can I retrieve the requested URL so I can call history.pushState on successful requests?


From this question (How to get request url in a jQuery $.get/ajax request) I found out that I can retrieve it with this.url.

From MDC window.history I found the syntax and from MDC Manipulating the browser history I found that I can get the current state with history.state (doesn't seem to work on Chrome though) and discovered that when calling pushState I can only send 640k characters on the stateObject or else it throws an exception.

My current method for successful ajax requests is:

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);
    }
},

For a basic test I am storing the entire result on the stateObject, if it throws an exception I will set the URL instead to be able to make a new request.

My popstate event is

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

It restores the page as it was previously, I don't need to make a new request.


The only way I can think of achieving this is by using jQuery to handle the click event of the links. So you could add a class attribute to your links as follows;

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

The add your click event;

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

Not very familar with the pushState signature but I believe using the href of the 'a' tag will work as a valid url to pass to the pushState.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜