簡體   English   中英

在jQuery Ajax上使用history.pushstate

[英]Using history.pushstate on jquery ajax

我有一個基於ajax的應用程序,其中我只有一個登錄頁面和主頁。

我的大多數鏈接都是“ ajaxed”的,我按如下方式完成它們:

//get the href of the link that has been clicked, ajaxify ANY links

$(document).on('click', '.tree a', function () {

            var link = $(this).attr('href');  //get the href off the list
            $.ajax({                          //ajax request to post the partial View
                url: link,
                type: 'POST',
                cache: false,
                success: function (result) {
                    $('#target').html(result);
                    $.validator.unobtrusive.parse($("form#ValidateForm"));
                }
            });
            return false; //intercept the link
   });

我想在我的應用程序上實現“ pushState”,到目前為止,我要做的第一步是添加以下代碼:

$(document).on('click', 'a', function () {
            history.pushState({}, '', $(this).attr("href"));
 });

現在,只要我單擊任何鏈接,就會更新我的地址欄,並且ajax內容會成功加載。 我對這個API有點陌生,所以我不知道我缺少什么,但是到目前為止,這是我的問題:

  1. 當我按下“返回”按鈕時,什么也沒發生。 我閱讀了有關“ popstate”的內容,並瀏覽了SO來尋找解決方案,但我似乎無法使它們正常工作。

  2. 當我單擊歷史記錄中的鏈接時,我獲得了子html的“原始”視圖,而沒有來自主html的布局。 如果我希望它像從主應用程序中單擊一樣顯示,該怎么辦?

我的大多數子視圖都是表格或列表。

此代碼應幫助您:

function openURL(href){

        var link = href;  //$(this).attr('href');                                    
        $.ajax({                                                             
            url: link,
            type: 'POST',
            cache: false,
            success: function (result) {
                $('#target').html(result);
                $.validator.unobtrusive.parse($("form#ValidateForm"));
            }
        });
        window.history.pushState({href: href}, '', href);
}

$(document).ready(function() {

   $(document).on('click', 'a', function () {
     openURL($(this).attr("href"));
     return false; //intercept the link
   });  

   window.addEventListener('popstate', function(e){
      if(e.state)
        openURL(e.state.href);
   }); 

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM