繁体   English   中英

更改页面并更改 URL 不刷新并在刷新后保留内容,如 ReactJS 网站

[英]Change page and change URL without refresh and keep content after refresh , like ReactJS website

我尝试使用 jQuery 的 load() function 来更改/加载内容而无需重新加载。 这行得通,但问题是:URL 保持不变!

即使我使用 history.pushState() 更改 URL,也不能解决问题。 例子:

用著名的window.history.pushState("object or string", "Title", "/new-url");

  1. 有了这个,我为每个页面创建了一个“假 URL”——如果我尝试再次进入这个更改过的 URL 的网站,我会收到一个错误,基本上链接不存在;
  2. 如果我刷新页面,我会丢失所有Ajax 加载的内容 - 我需要在刷新时保留内容;
  3. 当我点击更改 Ajax 加载页面时,不断将新链接放在前一个旁边,如发送的图像所示;
  4. 我想得到这个结果: https://reactjs.org/ - 传输页面,它们不会重新加载并且链接更改,它是可更新的并且链接单独工作 -我该怎么做

3) 我的页面及其 url 的打印屏幕

Important: index.html, about.html and contact.html are existing files that will load with the jquery function below.

HTML:

<div class="navbar">
    <div class="content">
        <div class="logo">My logo</div>
        <ul class="pages">
            <li id="index">Index</li>
            <li id="about">About us</li>
            <li id="contact">Contact</li>
        </ul>
    </div>
</div>

<section id="page"> 
    <div class="content">
        <!-- PAGES LOAD HERE -->
    </div>
</section>

<div class="footer">
    <div class="content">
        --Footer-- All rights reserved.
    </div>
</div>

JS:

    $(document).ready(function () {
        $('li').on("click", function () {
            $pageName = $(this).attr('id');
            $('#page .content').load(`pages/${$pageName}.html`);
            $('li').removeClass('active'); //only to remove the selection of actual page in CSS
            $(this).addClass('active'); //only to add the selection of actual page in CSS
            window.history.pushState("object or string", "Title", `pages/${$pageName}.html`);
        })

    })

您正在描述“路由”,这是与正在显示的内容匹配的 URL 的概念。

在 jquery 中,我建议使用谷歌搜索:jquery 路由器javascript router

如果您正在编写其他语言,则可以 google [language] router

最近谷歌正在提出https://www.npmjs.com/package/jqueryrouter现在正在转发到https://github.com/scssyworks/silkrouter

选择路由器后,请阅读文档并提出更多问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM