简体   繁体   中英

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. 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()

  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.

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

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.

If you are using apache 2.2.16+ it get's as simple as:

FallbackResource /index.html

This will rewrite all URL's to a single entry point that is index.html page.

Other solutions depend on the server you are running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM