如何一个Ajax请求之后更改URL? [英] How to change URL after an ajax request?
问题描述
我有一些链接,更新的div 内容的菜单
和执行功能的onSuccess
后,它被加载
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.ActionLink("Download", "Index", "download")</li>
如果我的网址 /家居
并单击下载链接股利变动成功。问题是,该URL不改变。
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.
我如何可以检索请求的URL,这样我可以叫 history.pushState
的成功请求?
How can I retrieve the requested URL so I can call history.pushState
on successful requests?
推荐答案
从这个问题(如何获得请求的URL在一个jQuery $不用彷徨/ Ajax请求)我发现我可以用 this.url
检索。
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
.
从 MDC window.history 我发现的语法和的MDC操纵浏览器历史记录我发现我可以用 history.state
的当前状态(似乎没有对铬的工作,虽然),发现打电话时 pushState
我只能发送640K字符的 stateObject
否则会抛出异常。
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.
我目前的方法成功的Ajax请求是:
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);
}
},
对于一个基本的测试,我存储在整个结果的 stateObject
,如果它抛出一个例外,我将设置URL反而能够使一个新的请求。
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.
我的 popstate
事件
$(window).bind("popstate", function (e) {
var state = e.originalEvent.state;
$("#body").html(state.html);
});
它恢复的页面,因为它是previously,我并不需要做一个新的请求。
It restores the page as it was previously, I don't need to make a new request.
这篇关于如何一个Ajax请求之后更改URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!