The principle of AJAX

  • Ajax stands for asynchronous javascript and XML, and today we generally use JSON instead of XML.
  • Commonly understood: in the web page using XMLHttpRequest objects and server data interaction, is Ajax.
  • AJAX is primarily used to make requests to the browser and receive responses without refreshing the page, and then partially update the page.
  • The advantage is that you can initiate a request and receive a response without refreshing.

Ii.AJAX usage method

Making an AJAX request with JS is a simple four-step process

The first step is creating an XMLHttpRequest object

const request = new XMLHttpRequest();
Copy the code

Step 2 The open method sets the parameters

request.open("GET","/style.css")
Copy the code

The third step listens for a successful request and accepts the response

request.onreadystatechange = ()=>{ if(this.readyState === 4){ if (this.status >= 200 && this.status<300) { console.log(request.response); } else {alert(" request failed "); }}Copy the code

Step 4 Send the request

request.send();
Copy the code

Three. A life of one request

The request has different readyStates at different stages, which makes it easier to understand the onreadyStateChange event

Different stages of a request readyState
let request = new XMLHttpRequest() 0(The proxy is created, but the open method is not called)
request.open(‘GET’, ‘/style.css’) 1(the open method is called)
request.send() 2(send method is called)
The first response message appears in the browser 3(Downloading)
There is a response download complete 4(Download completed)

A readyState of 4 indicates that the request is complete, and we can then use the request status code to determine whether the request was successful or not.

In actual four.

Requesting CSS files

The focus is on what to do with the received response: generate the style tag

getCss.onclick = () => { const request = new XMLHttpRequest(); request.open("GET", "style.css"); request.onreadystatechange = () => { if (request.readyState === 4) { if (request.status >= 200 && request.status < 300) { const style = document.createElement("style"); style.innerHTML = request.response; document.body.appendChild(style); } else {alert(" CSS request failed "); } } } request.send(); }Copy the code

Request JS file

The focus is on what to do with the received response: generate a script tag

getHTML.onclick = () => { const request = new XMLHttpRequest(); request.open("GET", "index.js"); request.onreadystatechange = () => { if (request.readyState === 4) { if (request.status >= 200 && request.status < 300) { const script = document.createElement("script"); script.src = request.response; document.body.appendChild(script); } else {alert(" request JS failed "); } } } request.send(); }Copy the code

Requesting HTML files

getHTML.onclick = () => { const request = new XMLHttpRequest(); request.open("GET", "index.html"); request.onreadystatechange = () => { if (request.readyState === 4) { if (request.status >= 200 && request.status < 300) { const div = document.createElement("div"); div.innerHTML = request.response; document.body.appendChild(div); } else {alert(" CSS request failed "); } } } request.send(); }Copy the code

Request JSON file

Json. parse converts JSON syntax strings to jSON-typed data. Json. stringify converts JS data to JSON strings

getJSON.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET', 'index.json')
    request.onreadystatechange = () => {
        if (request.readyState === 4) {
            if (request.status === 200) {
                const obj = JSON.parse(request.response);
            }
        }
    }

    request.send()
}
Copy the code

Use XMLHttpRequest to encapsulate Ajax

function ajax(url, method) { return new Promise((resolve, reject) => { let request = new XMLHttpRequest(); request.open(method, url); request.onreadystatechange = () => { if (request.readyState === 4) { if (request.status >= 200 && request.status < 300) { resolve(request.responseText); }} else {reject(reject); }}; request.send(); }); }Copy the code