【发布时间】:2023-02-02 02:33:22
【问题描述】:
我正在尝试用 html、css 和 vanilla JS 制作一个 SPA(我对 JS 知之甚少)。我遇到的问题是我正在使用的方法可以正常工作,但是当我在新选项卡中打开其中一个部分时,它无法正确寻址网络并给出错误“无法获取”。 有什么办法可以简单地解决这个问题,只用香草 js 吗?
const route = (event) => {
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
handleLocation();
};
const routes = {
404: "./pages/404.html",
"/": "./pages/index.html",
"/vehicles": "./pages/vehicles.html",
"/services": "./pages/services.html",
"/contact": "./pages/contact.html",
"/financing": "./pages/financing.html",
"/locations": "./pages/locations.html",
};
const handleLocation = async () => {
const path = window.location.pathname;
const route = routes[path] || routes[404];
const html = await fetch(route).then((data) => data.text());
document.getElementById("main-page").innerHTML = html;
};
window.onpopstate = handleLocation;
window.route = route;
handleLocation();
【问题讨论】:
标签: javascript single-page-application