簡體   English   中英

歷史API和History.js后退按鈕問題

[英]History API and History.js Back Button issue

我正在通過Ajax加載頁面。 當用戶單擊鏈接時,頁面正在成功加載AJAX,但是當用戶單擊后退按鈕時,頁面將重新加載初始頁面。 所以場景就是這樣。

  1. 加載初始頁面(index.php)
  2. 用戶點擊鏈接
  3. 頁面加載成功
  4. 單擊“后退”按鈕
  5. 初始頁面現在顯示兩次。

這是標記。

    $(function() {
            // Prepare
            var History = window.History; // Note: We are using a capital H instead of a lower h
            if (!History.enabled) {
                // History.js is disabled for this browser.
                // This is because we can optionally choose to support HTML4 browsers or not.
                return false;
            }

            // Bind to StateChange Event
            History.Adapter.bind(window, 'statechange', function() { // Note: We are using statechange instead of popstate
                var State = History.getState();
                $('#content').load(State.url);
            });

            $('a').click(function(evt) {
                evt.preventDefault();
                History.pushState(null, $(this).text(), $(this).attr('href'));
                alert(State.url)
            });
        });

這是標記

   <div id="wrap">
            <a href="page1.html">Page 1</a>
        </div>

        <div id="content">
            <p>Content within this box is replaced with content from
                supporting pages using javascript and AJAX.</p>
        </div>

如果你仍然沒有得到我的問題或情景

這是完整的方案。 初始頁面

在此輸入圖像描述

當用戶單擊鏈接時,所選頁面成功加載

在此輸入圖像描述

當我單擊后退按鈕時,初始頁面現在加倍

在此輸入圖像描述

如您所見,“Page1”鏈接加倍。 這是一個瀏覽器問題嗎? 或者我對歷史api的不足之處是缺乏或缺失的東西? 這有什么可能的解決方案?

如果構建站點以對主頁面和內容頁面使用類似的模板,則可以使用jquery.load的容器選擇器語法:

// See: http://api.jquery.com/load/
$('#result').load('ajax/test.html #container');

在您的情況下會導致:

$('#content').load(State.url + ' #content');

這將帶來額外的好處,即內容URL頁面也可以直接訪問,而不會增加太多技巧。

這可能發生,因為當你向后導航時它將觸發'statechange'事件,並且在你的回調中你正在用給定的url加載該頁面的內容: $('#content').load(State.url); ,所以,當你向后導航到/ URL時,它會加載該索引頁面的內容並將其放在容器中,所以你的標記實際上如下所示:

<div id="wrap">
        <a href="page1.html">Page 1</a>
</div>

<div id="content">
    <div id="wrap">
        <a href="page1.html">Page 1</a>
    </div>

    <div id="content">
        <p>Content within this box is replaced with content from
            supporting pages using javascript and AJAX.</p>
    </div>
</div>

有幾種方法可以解決這個問題 - 最簡單的方法就是檢測用戶是否導航到初始頁面並且不通過ajax加載此頁面,而是插入預定義的內容。 您還可以在服務器端檢測是否通過ajax發出請求,然后僅返回更新頁面所需的內容(在您的情況下可能是<p>Content within this box is replaced with content from supporting pages using javascript and AJAX.</p>

 $(function() {
            // Prepare
            var History = window.History; // Note: We are using a capital H instead of a lower h
            if (!History.enabled) {
                // History.js is disabled for this browser.
                // This is because we can optionally choose to support HTML4 browsers or not.
                return false;
            }

            // Bind to StateChange Event
            History.Adapter.bind(window, 'statechange', function() { // Note: We are using statechange instead of popstate
                var State = History.getState();
                if(State.url==document.URL){
                    $.ajax({
                          url: State.url,
                          success: function(data) {
                                        var dom_loaded=$(data);
                                        $('#content').html($('#content',dom_loaded).html());
                          }
                        });


                }else{
                    $('#content').load(State.url);
                }
            });

            $('a').click(function(evt) {
                evt.preventDefault();
                History.pushState(null, $(this).text(), $(this).attr('href'));
                alert(State.url)
            });
        });

試試這個js。

我遇到了類似的問題。 我只是添加了$ content.html(“”)來清除容器,然后通過ajax加載它。 請參閱由Joel添加的片段相關部分, 以便在后退按鈕上修復內容加載兩次

$.ajax({
            url: url,
            success: function (data, textStatus, jqXHR) {
                // Prepare
                var 
                    $data = $(documentHtml(data)),
                    $dataBody = $data.find('.document-body:first'),
                    $dataContent = $dataBody.find(contentSelector).filter(':first'),
                    $menuChildren, contentHtml, $scripts;

                // Fetch the scripts
                $scripts = $dataContent.find('.document-script');
                if ($scripts.length) {
                    $scripts.detach();
                }

                // Fetch the content
                contentHtml = $dataContent.html() || $data.html();
                if (!contentHtml) {
                    document.location.href = url;
                    return false;
                }

                // Update the menu
                $menuChildren = $menu.find(menuChildrenSelector);
                $menuChildren.filter(activeSelector).removeClass(activeClass);
                $menuChildren = $menuChildren.has('a[href^="' + relativeUrl + '"],a[href^="/' + relativeUrl + '"],a[href^="' + url + '"]');
                if ($menuChildren.length === 1) { $menuChildren.addClass(activeClass); }

                // Update the content
                $content.stop(true, true);
                //added by Joel to fix content loading twice on back button
                $content.html("");
                //end added by joel
                $content.html(contentHtml).ajaxify().css('opacity', 100).show(); /* you could fade in here if you'd like */

                // Update the title
                document.title = $data.find('.document-title:first').text();
                try {
                    document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<', '&lt;').replace('>', '&gt;').replace(' & ', ' &amp; ');
                }
                catch (Exception) { }

                // Add the scripts
                $scripts.each(function () {
                    var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
                    scriptNode.appendChild(document.createTextNode(scriptText));
                    contentNode.appendChild(scriptNode);
                });

                // Complete the change
                if ($body.ScrollTo || false) { $body.ScrollTo(scrollOptions); } /* http://balupton.com/projects/jquery-scrollto */
                $body.removeClass('loading');
                $window.trigger(completedEventName);

                // Inform Google Analytics of the change
                if (typeof window._gaq !== 'undefined') {
                    window._gaq.push(['_trackPageview', relativeUrl]);
                }

                // Inform ReInvigorate of a state change
                if (typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined') {
                    reinvigorate.ajax_track(url);
                    // ^ we use the full url here as that is what reinvigorate supports
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                document.location.href = url;
                return false;
            }
        }); // end ajax

我正在使用此代碼,希望這對您有所幫助。

   //get the contents of #container and add it to the target action page's #container
    $('#container').load(url+' #container',function(){
        $('#container').html($(this).find('#container').html());
    });

暫無
暫無

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

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