Javascript fetch 在 window.popstate 上获取未定义的 URL



我正在尝试从php页面获取内容。我有一个获取调用 + 一个 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将数据对象作为第一个参数,而不是字符串 - try history.pushState({url:e.currentTarget.getAttribute("href"(} 则 e.state.url 将等于您要加载的 url。

最新更新