我有一个带有一些链接的菜单,这些链接更新 div content
并在加载后执行函数 onSuccess
。
<li>@Ajax.ActionLink("Home", "Index", "home")</li>
<li>@Ajax.ActionLink("Download", "Index", "download")</li>
如果我在 url /home
上并单击下载链接,div 更改成功。问题是 URL 没有改变。
如何检索请求的 URL,以便在请求成功时调用 history.pushState
?
最佳答案
来自 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
时我只能发送 640k 个字符在 stateObject
上,否则它会抛出异常。
我目前成功的 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);
});
它将页面恢复为之前的状态,我不需要提出新的请求。
关于c# - 如何在 ajax 请求后更改 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5525890/