【问题标题】:HTML5 History API initial load issueHTML5 History API 初始加载问题
【发布时间】:2014-09-28 19:32:59
【问题描述】:

我正在尝试在页面首次加载时存储第一页信息。这样当我点击第二页时,我可以找回第一页的信息。

(Initial Page -> Page2 -> Initial Page)

经过几个小时的工作,我决定存储一个名为 firstLoad 的全局变量,并使用 replaceState 而不是 pushState。现在可以了。但是有一个问题,不能这样:

Initial Page -> Page2 -> Page3 -> Page2

Page 3回到Page 2时,控制台显示:

GET http://localhost/[object%20Object] 404 (Not Found) 

我用谷歌搜索过,但找不到任何合适的教程来处理这个问题,他们中的大多数人建议使用 history.js,但我正在尝试先了解它是如何工作的。任何帮助将不胜感激!

<script>
$(function(){
    var firstLoad = 1;

    $('a').on('click', function(e){ 
        e.preventDefault();
        var path = this.href;
        var currentPath = window.location.pathname;
        loadContent(path);

        if(firstLoad==1){
            console.log(firstLoad);
            console.log(currentPath);
            firstLoad=0;
            history.replaceState(currentPath, '', '');
            history.pushState({},'',path);
        }else{
            console.log('Not first load')
            history.pushState(path,'',path);
        }
    });

    //Pop State
    $(window).on('popstate', function(e){
        var state = e.originalEvent.state;
        if(e.originalEvent && state){
            loadContent(state);
        }
    });

    //Load Content
    function loadContent(path){
        $.get(path, function(data){
            $('#result').html(data);
        });
    };

});
</script>

【问题讨论】:

    标签: javascript jquery html history.js html5-history


    【解决方案1】:

    问题出在这部分代码中。

    $(window).on('popstate', function(e){
        var state = e.originalEvent.state;
        if(e.originalEvent && state){
            loadContent(state);
        }
    });
    

    如果我们检查MDN page on Window.onpopstate,我们会发现state 事件属性是传递给pushState 等函数的状态对象。

    popstate 事件的 state 属性包含历史条目的 state 对象的副本。

    表示jQuery事件对象属性e.originalEvent.state是你在pushState上传入的对象。您可以使用此对象来存储数据,但您的 loadContent 函数需要一个字符串作为 URL,而不是对象。

    我认为您实际上想在您的 popstate 处理程序中使用 document.location

    $(window).on('popstate', function(e){
        loadContent(document.location);
    });
    

    【讨论】:

    • 现在明白了!谢谢亚历克斯!抛开这个问题不谈,对于初始页面,除了声明全局变量 firstload = 1,还有什么更好的方法吗?
    • @DaleA.Almaraz 我认为您在初始加载时不需要做不同的事情,但我不确定我是否理解问题所在。您可以发布一个新问题,特别是关于该问题的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多