Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript History API和History.js返回按钮问题_Javascript_Jquery_Ajax_History.js - Fatal编程技术网

Javascript History API和History.js返回按钮问题

Javascript History API和History.js返回按钮问题,javascript,jquery,ajax,history.js,Javascript,Jquery,Ajax,History.js,我正在通过Ajax加载页面。当用户单击链接时,页面将成功加载AJAX,但当用户单击后退按钮时,页面将重新加载初始页面。所以情况是这样的 加载初始页面(index.php) 用户点击链接 页面加载成功 单击后退按钮 最初的页面现在显示两次 这是加价 $(function() { // Prepare var History = window.History; // Note: We are using a capital H instead

我正在通过Ajax加载页面。当用户单击链接时,页面将成功加载AJAX,但当用户单击后退按钮时,页面将重新加载初始页面。所以情况是这样的

  • 加载初始页面(index.php)
  • 用户点击链接
  • 页面加载成功
  • 单击后退按钮
  • 最初的页面现在显示两次
  • 这是加价

        $(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>
    
    
    此框中的内容将替换为中的内容
    支持使用javascript和AJAX的页面

    如果你仍然不明白我的问题或场景

    下面是完整的场景。 首页

    当用户单击链接时,所选页面将成功加载

    当我点击后退按钮时,初始页面现在翻了一倍


    如您所见,“Page1”链接翻了一倍。这是浏览器问题吗?或者我对历史api的理解缺失了什么?可能的解决方案是什么?

    这可能会发生,因为当您向后导航时,它将触发“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>
    
    
    此框中的内容将替换为中的内容
    支持使用javascript和AJAX的页面

    有几种方法可以解决这个问题——最简单的方法就是检测用户是否导航到初始页面,而不是通过ajax加载此页面,而是插入预定义的内容。 您还可以在服务器端检测请求是否是通过ajax发出的,然后只返回更新页面所需的内容(在您的情况下可能是
    此框中的内容将替换为使用javascript和ajax的支持页面中的内容。


    试试这个js。

    如果您构建的站点在主页和内容页上都使用类似的模板,那么您可以使用jquery.load的容器选择器语法:

    // See: http://api.jquery.com/load/
    $('#result').load('ajax/test.html #container');
    
    在您的情况下,会导致:

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

    这将有一个额外的好处,即内容url页面也可以直接访问,而无需增加很多技巧。

    我也遇到了类似的问题。我只是添加了$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
    
    $.ajax({
    url:url,
    成功:函数(数据、文本状态、jqXHR){
    //预备
    变量
    $data=$(documentHtml(data)),
    $dataBody=$data.find('.documentbody:first'),
    $dataContent=$dataBody.find(contentSelector.filter)(“:first”),
    $menuChildren,contentHtml,$scripts;
    //取脚本
    $scripts=$dataContent.find('.documentscript');
    if($scripts.length){
    $scripts.detach();
    }
    //获取内容
    contentHtml=$dataContent.html()| |$data.html();
    如果(!contentHtml){
    document.location.href=url;
    返回false;
    }
    //更新菜单
    $menuChildren=$menu.find(menuChildrenSelector);
    $menuChildren.filter(activeSelector).removeClass(activeClass);
    $menuChildren=$menuChildren.has('a[href^=“”+relativeUrl+”],a[href^=“/”+relativeUrl+”],a[href^=“””+url+”);
    如果($menuChildren.length==1){$menuChildren.addClass(activeClass);}
    //更新内容
    $content.stop(true,true);
    //Joel添加了修复内容加载两次的后退按钮
    $content.html(“”);
    //结束由乔尔添加
    $content.html(contentHtml.ajaxify().css('opacity',100).show();/*如果您愿意,可以在这里淡入淡出*/
    //更新标题
    document.title=$data.find('.document title:first').text();
    试一试{
    document.getElementsByTagName('title')[0]。innerHTML=document.title.replace('','').replace('&','&;');
    }
    捕获(异常){}
    //添加脚本
    $scripts.each(函数(){
    var$script=$(this),scriptText=$script.text(),scriptNode=document.createElement('script');
    appendChild(document.createTextNode(scriptText));
    appendChild(scriptNode);
    });
    //完成更改
    如果($body.ScrollTo | | false){$body.ScrollTo(scrollOptions)}/*http://balupton.com/projects/jquery-scrollto */
    $body.removeClass('load');
    $window.trigger(completedEventName);
    //将变更通知谷歌分析
    如果(窗口类型).\u gaq!=“未定义”){
    窗口。_gaq.push([''u trackPageview',relativeUrl]);
    }
    //通知重振状态变化
    if(typeof window.reinviorate!=“未定义”&&typeof window.reinviorate.ajax\u track!=“未定义”){
    重振.ajax_轨道(url);
    //^我们在此处使用完整的url,因为这是Renivirate支持的内容
    }
    },
    错误:函数(jqXHR、textStatus、errorThr
    
    $.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());
        });