【问题标题】:jQuery history pushstate and reloading issuejQuery历史推送状态和重新加载问题
【发布时间】:2017-06-26 07:09:10
【问题描述】:

我正在使用 html5s 历史记录。推送状态以使用带有单页应用程序的浏览器后退按钮(我正在使用cordova)。所以我试图在 div 容器中动态加载内容。

根据这个例子,我有一个历史堆栈:-

https://zinoui.com/demo/pushstate/

(在下面的 cmets 中有人遇到了同样的问题:- https://zinoui.com/blog/single-page-apps-html5-pushstate)

我的 html 内容是单独的 html 文件。

在我按下 f5 或浏览器重新加载/刷新按钮之前,一切正常。在页面重新加载时,我得到一个 404,因为浏览器尝试调用假 url,它并没有真正退出。 似乎浏览器想要在自己而不是在 index.html 中加载子页面。 在上面的示例中,作者在 html 文件中没有动态加载的内容。他从某个地方收到了 html 代码作为响应,我不确定他是如何做到的。

所以,我想重新加载我的页面,并将单独页面中的内容仍在 index.html 的指定区域中

这是我的代码: 索引.js:

   $(function () {

            var load = function (url) {
                $.get(url).done(function (data) {
                    $("#content").html(data);
                })
            };


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

                    e.preventDefault();
                    console.log(history);
                    var $this = $(this),
                        url = $this.attr("id"),
                        title = $this.text();


                    history.pushState({
                        url: url,
                        title: title
                    }, title, url);

                    document.title = title;

                        //here you can see the folder structure
                        load("/pages/" + url + "/" + url + ".html");



                });


            $(window).on('popstate', function (e) {

                var state = e.originalEvent.state;
                if (state !== null) {
                    document.title = state.title;
                    load(state.url);

                }
                else {
                    document.title = 'example title';

                }
            });


        });

index.html:

...

 <div id="content">

</div>

....

来自另一个 html 文件的链接(主菜单也从 index.html 加载到 content-div 中)

  <li><a id="sp_termine">&Uuml;bersicht der Termine</a></li>
  <li><a id="sp_termine_aendern">Termin &auml;ndern</a></li>

我真的很期待得到一些帮助!
谢谢

【问题讨论】:

  • 请发布您遇到问题的代码,以便我们查看您正在使用的内容。

标签: javascript jquery html cordova


【解决方案1】:

1.解决方案:

不要伪造网址到不存在的位置。它的风格很糟糕。使用查询 (?) 或 # :

index.html#mycoolsubsite
index.html?mycoolsubsite

简单地做:

window.location="#mycoolsubsite";

如果页面重新加载,您可能需要检查 url 是否指向子站点:

alert(window.location.split("#")[1] || "main"); //will print "main" or if you 'redirected' "mycoolsubsite"

2。解决方案:

学习 php 或 nodejs 并实现一个路由器。

【讨论】:

    猜你喜欢
    • 2012-05-18
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2013-10-01
    • 2020-03-07
    • 2012-10-13
    • 1970-01-01
    • 2013-10-02
    相关资源
    最近更新 更多