I
I
Ivan Ivanovich2020-05-01 13:43:25
JavaScript
Ivan Ivanovich, 2020-05-01 13:43:25

Do-it-yourself Ajax menu?

Hello.

For the first time I am making a site on ajax, I wrote a script and I wanted to ask a couple of questions.

function load(url){
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = ()=>{
      if (xhr.readyState == XMLHttpRequest.DONE){
         if (xhr.status == 200) {
             document.body.innerHTML = xhr.responseText;
             history.pushState('', '', url);
         }
         else if (xhr.status === 400) {
            alert('There was an error 400');
         }
      }
  };

  xhr.open('GET', url, true);
  xhr.send();
}


2 questions:

1. Let's imagine the page index, about. Both have links href="about.html" and href="/" respectively.
If I click the link while on the index page, I end up on about, but if I click the link again, the reload will already occur, although all preventdefaul links and at the end of each page a file with a script is loaded.

2. I did not find a way how to implement back and forth arrows. At the moment, this site is my reference. I don't want to hash (#) in links. Please tell me how you can implement transitions exactly by the buttons of the browser, how to implement it on the page, I know (history back. forward).

Please tell me how to solve the problem that I described in the first question and in the second, where the problem is with the transition using browser buttons.

Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-05-01
@IwanQ

in short lol I sketched a fiddle, but it works in an iframe, and there is no access to pushState
exactly this site on vue.js, there is already a built-in so-called "router" that does exactly what is needed, here you can briefly see
https://router .vuejs.org/ru/
here is the fiddle, only it doesn't work :D

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question