The principle of AJAX

  • AJAX is short for asynchronous JS and XML, and we usually use JSON instead of XML these days.

  • AJAX is primarily used to make a request to the browser, receive a response, and then partially update the page without refreshing the page.

  • The core concept of the technique is the XMLHttpRequest object, which makes HTTP requests, and we listen for changes in its readystate to get a response.

  • The specific code is analyzed in the second part

  • The advantage is that the request can be made and the response received without refreshing.

  • The disadvantage is that it is limited by the browser and cannot cross domains.

Two, use method

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

  1. Create an XMLHTTPRequest object
let request = new XMLHttpRequest()
Copy the code
  1. Setting request parameters
request.open('GET'.'/style.css')
Copy the code
  1. Listen for status changes after a successful request
request.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(request.response)
  }
};
Copy the code
  1. Send the request
request.send()
Copy the code

A life of asking

The third step onreadyStateChange event is better understood by knowing that requests have different Readystates at different stages

Different phases of the request readyState
let request = new XMLHttpRequest() 0
request.open(‘GET’, ‘/style.css’) 1
request.send() 2
The first response message appears in the browser 3
All responses are downloaded 4

Load the CSS

getCSS.onclick = () = > {
    const request = new XMLHttpRequest()
    request.open('GET'.'/style.css')
    request.onreadystatechange = () = > {
        // If the request succeeds
        // The download is complete, but I don't know whether it is 200 or 404
        if (request.readyState === 4) {
            if (request.status >= 200 && request.status < 300) {
                // The request was sent successfully
                // Write the CSS content to the style tag and insert the head
                const style = document.createElement('style')
                // How to get the corresponding content? request.response
                style.innerHTML = request.response
                document.head.appendChild(style)
            } else {
                // The request failed
                alert("Failed to load CSS");
            }
        }

    }
    request.send()
}
Copy the code

The key is what to do with the response you get: generate the style tag

4. Load JS

The key is what to do with the response: generate a script tag

getJS.onclick = () = > {
    console.log('111')
    const request = new XMLHttpRequest()
    request.open('GET'.'/2.js')
    request.onreadystatechange = () = > {
        // The download is complete, but I don't know whether it is 200 or 404
        if (request.readyState === 4) {
            if (request.status >= 200 && request.status < 300) {
                // The request was sent successfully
                // Write the js content to the script tag and insert the head
                const script = document.createElement('script')
                // How to get the corresponding content? request.response
                script.innerHTML = request.response
                document.body.appendChild(script)
            } else {
                // The request failed
                alert("Failed to load JS");
            }
        }
    }
    request.send()
}
Copy the code

Load HTML

Create a new div, set div.innerHTML = response, and appendChild to that location

getHTML.onclick = () = > {
    const request = new XMLHttpRequest()
    request.open('GET'.'/3.html')
    request.onload = () = > {
        const div = document.createElement('div')
        div.innerHTML = request.response
        document.body.appendChild(div)
    }
    request.onerror = () = > {
    }
    request.send()

}
Copy the code

Load JSON

Json. parse converts strings that conform to JSON syntax into JS data of the corresponding type

Json. stringify turns JS data into a JSON string

getJSON.onclick = () = > {
    const request = new XMLHttpRequest()
    request.open('GET'.'/5.json')
    request.onreadystatechange = () = > {
        if (request.readyState === 4) {
            if (request.status === 200) {
                // The request succeeded
                // How to parse JSON? Json. parse: string -> JS object
               
                const obj = JSON.parse(request.response);
            

            }
        }
    }

    request.send()
}
Copy the code

Practice AJAX code at github.com/dandanloveJ…