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



我曾尝试使用jQuery的load((函数在不重新加载的情况下更改/加载内容。这是可行的,但问题是: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 的打印屏幕

重要提示:index.html、about.html和contact.html是将使用下面的jquery函数加载的现有文件。

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

如果你正在写其他语言,你可以在[language] router上搜索。

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

一旦你选择了一个路由器,请阅读文档,并提出更多问题。

最新更新