[英]How to reload the page when implementing the History API
I am trying to use the History API to allow me to use the back and forward buttons when loading content dynamically. 我试图使用History API允许我在动态加载内容时使用后退和前进按钮。 Here is the code I am using, and an example of the state object I am using too.
这是我正在使用的代码,以及我正在使用的状态对象的示例。
How I am using the state object and pushstate()
我如何使用状态对象和
pushstate()
var stateObj = {Content : homeSection.innerHTML, "Product" : detail.Name, Title : title.innerHTML, Section:"dynamicArticle"};
window.history.pushState(stateObj, "", detailName);
window.addEventListener('popstate', function(event) {
updateContent(event.state);
});
Function used: 使用的功能:
function updateContent(stateObject) {
if (stateObject){
homeSection = document.getElementById(stateObject.Section);
homeSection.innerHTML = stateObject.Content;
title.innerHTML = stateObject.Title;
var items = document.querySelectorAll(".homeItem");
if(items){
for(i=0; i<items.length; i++){
items[i].addEventListener("click", selectedProduct);
}
}
checkoutButton = document.getElementById('checkoutButton');
if(checkoutButton){
checkoutButton.addEventListener('click', function(){
displayCheckout();
});
}
basketButton = document.getElementById("basketButton");
quantityInput = document.getElementById("productQuantity");
if(basketButton){
basketButton.addEventListener('click', clicked);
basketButton.addEventListener('click', updateBasketNumber);
quantityInput.value = "1";
}
searchSort = document.getElementById("sort");
if(searchSort){
var items = document.querySelectorAll(".searchResult");
for(i=0; i<items.length; i++){
items[i].addEventListener("click", selectedProduct);
}
searchSort.addEventListener("change", function(){
sort = searchSort.value;
searchItem(e, sort);
});
}
}
else{
return;
}
}
What I am struggling with is that if I navigate to one of the pages using the pushState()
and I try to reload the page, as you would expect the page cannot be found. 我正在苦苦挣扎的是,如果我使用
pushState()
导航到其中一个页面,然后尝试重新加载该页面,因为您希望找不到该页面。
I am asking if there is a way to allow a reload or for someone to navigate to the URL without it giving an error, and giving the correct content 我在问是否有一种方法可以允许重新加载,或者有人可以导航到该URL而不会产生错误,并提供正确的内容
Just like @jon-koops pointed in the comment you need to configure your server to redirect requests to the same page where all you links branch. 就像@ jon-koops在注释中指出的一样,您需要配置服务器以将请求重定向到所有链接分支到的同一页面。
If you are using apache 2.2.16+
it get's as simple as: 如果您使用的是Apache
2.2.16+
它将变得非常简单:
FallbackResource /index.html
This will rewrite all URL's to a single entry point that is index.html
page. 这会将所有URL重写为单个入口点,即
index.html
页面。
Other solutions depend on the server you are running. 其他解决方案取决于您正在运行的服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.