6

Ajax経由でページを読み込んでいます。ユーザーがリンクをクリックすると、ページはAJAXで正常に読み込まれますが、ユーザーが[戻る]ボタンをクリックすると、ページは最初のページを再読み込みします。シナリオはこれです。

  1. 最初のページをロードする(index.php)
  2. ユーザーがリンクをクリックします
  3. ページが正常に読み込まれます
  4. [戻る]ボタンをクリックします
  5. 現在、最初のページが2回表示されています。

これがマークアップです。

    $(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>

それでも私の質問やシナリオがわからない場合

これが完全なシナリオです。最初のページ

ここに画像の説明を入力してください

ユーザーがリンクをクリックすると、選択したページが正常に読み込まれます

ここに画像の説明を入力してください

戻るボタンをクリックすると、最初のページが2倍になります

ここに画像の説明を入力してください

ご覧のとおり、「Page1」リン​​クは2倍になっています。これはブラウザの問題ですか?または、履歴APIの私の理解は、何かが欠けているか、欠けていますか?これに対する可能な解決策は何ですか?

4

5 に答える 5

5

メインページとコンテンツページの両方に同様のテンプレートを使用するようにサイトを構築する場合は、jquery.loadのコンテナーセレクター構文を使用できます。

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

あなたの場合、次のような結果になります。

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

これには、多くのトリックを追加することなく、コンテンツのURLページに直接アクセスできるという追加の利点があります。

于 2012-12-29T21:26:27.810 に答える
1

これは、逆方向に移動すると「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 を介してこのページを読み込まず、定義済みのコンテンツを挿入することです。<p>Content within this box is replaced with content from supporting pages using javascript and AJAX.</p>リクエストがajaxを介して行われたかどうかをサーバー側で検出し、ページの更新に必要なコンテンツのみを返すこともできます(あなたの場合は.

于 2012-12-27T11:03:34.743 に答える
0
 $(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を試してください。

于 2012-12-27T11:42:53.130 に答える
0

私は同様の問題を抱えていました。$content.html("") を追加して、コンテナを ajax 経由でロードする前にクリアしました。//で始まる関連セクションのスニペットを参照してください

$.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
于 2012-12-30T21:05:45.257 に答える
0

私はこのコードを使用しています。これがお役に立てば幸いです。

   //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());
    });
于 2015-03-12T06:47:13.697 に答える