javascript - Javascript 在 window.popstate 上获取未定义的 URL
问题描述
我正在尝试从 php 页面获取内容。我有一个 fetch 调用 + 一个 history.pushState 在点击时触发,它们都工作正常,但是 window.popstate 在通过按下浏览器的后退按钮返回时返回错误。错误是,window.popstate 不知道返回时要获取的 url。
不幸的是,我不知道如何将正确的url变量传递给 window.popstate。
// the code stripped fetch function
var load = function(url){
fetch(url, {
method: "GET"
}).then(function(response) {
response.text().then(function(text) {
// parsing and temporary placing fetched content into a fragment
var content = new DOMParser().parseFromString(text, "text/html"),
bodyPart = content.querySelector('main'),
fragmentElement = document.createDocumentFragment(),
tempElement = fragmentElement.appendChild(bodyPart);
// replacing the current content with the fragment
document.body.replaceChild(tempElement, document.querySelector('main'));
// need to assign the fetch on click function again, otherwise it won't work on the dynamically added (the fetched) links
clickOnPJAXLink();
});
});
}
// the click function if clicking on any link function to start fetching content
var clickOnPJAXLink = function(url) {
document.querySelectorAll('A').forEach(a => {
a.addEventListener('click', (e) => {
e.preventDefault();
var url = e.currentTarget.getAttribute("href");
load(url);
history.pushState(url, "sometitle", url);
});
});
}
// load the function initially on the home page
clickOnPJAXLink();
// popstate for back button
window.addEventListener('popstate', function (e) {
var state = e.state;
if (state !== null) {
load(url);
console.log(url)
}
});
window.popstate 返回错误,即var url未定义,因此当然无法获取之前(历史回溯)的内容。
非常感谢任何提示!
解决方案
history.pushState 将数据对象作为第一个参数,而不是字符串-尝试 history.pushState({url:e.currentTarget.getAttribute("href")} 然后 e.state.url 将等于您要加载的 url。
推荐阅读
- python - 在python中连接字符串时出现错误
- php - 为什么在将 html 页面导出为 word 时出现错误?
- google-sheets - 逐月百分比变化的计算字段
- mysql - 更新后触发插入额外记录(使用 mySQLWorkbench)
- php - 在一台服务器 Laravel 中的两个项目之间调用 curl
- python - 在以下代码中定义 tensorflow 2.+ 中的损失函数的正确方法是什么?
- html - 弹性列容器中项目之间的间距
- javascript - Puppeteer:for 循环 - 语法问题
- html - 背景图像 (CSS) 不会出现在网站上
- python-3.x - Selenium Wire Chrome 驱动程序失去互联网连接