c# - 如何在 ajax 请求后更改 URL?

标签 c# jquery asp.net-mvc ajax asp.net-mvc-3

我有一个带有一些链接的菜单,这些链接更新 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/

相关文章:

jquery - 如何从元素中获取内联 CSS 样式属性

c# - HashAlgorithm.Create 在 C# ASP.NET Core 2 中因 PlatformNotSupportedException 而失败

javascript - jquery 在输入单击时添加类并在单击其他输入时删除类

c# - 使用 HttpPost 注释?修复它不会破坏页面

C#:在同一条语句中动态实例化不同的类?

c# - 如何从 mp4 FileStream 对象中提取持续时间(不存储在文件系统中)

javascript - 我怎样才能阻止这个 jQuery 出问题?

c# - 正则表达式匹配 4 组中的 2 组

asp.net-mvc - 阻止 Html.ValidationSummary() 更改验证消息的顺序

c# - 如何从 Azure 自动化中的 Runbook 调用 DLL 中的 C# 方法?