【问题标题】:How to change URL after an ajax request?ajax请求后如何更改URL?
【发布时间】:2011-07-28 09:47:27
【问题描述】:

我有一个带有一些链接的菜单,这些链接会更新 div content 并在加载后执行函数 onSuccess

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

如果我在 URL /home 上并单击下载链接,则 div 更改成功。问题是 URL 没有改变。

如何检索请求的 URL,以便在成功请求时调用 history.pushState

【问题讨论】:

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


    【解决方案1】:

    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 来处理链接的点击事件。因此,您可以向链接添加类属性,如下所示;

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

      添加你的点击事件;

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

      对 pushState 签名不是很熟悉,但我相信使用“a”标签的 href 可以作为传递给 pushState 的有效 url。

      【讨论】:

        猜你喜欢
        • 2011-01-17
        • 1970-01-01
        • 1970-01-01
        • 2021-05-02
        • 2021-01-15
        • 1970-01-01
        • 1970-01-01
        • 2011-08-28
        • 2010-12-01
        相关资源
        最近更新 更多