Ajax overview

background

  • Until we get to AJAX, we can simply say “JavaScript is limited,” because until then all the apis provided by the Web platform were at a “stand-alone” stage.

This can result in some unachievable features, such as:

  • When the user login function is not implemented, the profile picture of the user is displayed when the user enters the email address.
  • Cannot implement the user registration function, when the user enters the mailbox or user name prompt exists
  • Unable to realize the message board function, real-time to see the latest user messages.

The development of these features is stuck with the same problem

  • The data is stored on the server and cannot be obtained through known apis

demand

  • Make a request to the server and receive a response from the server
  • If you can send network requests directly through JS, then the web will be more possible, and with it, more functions can be realized, at least not only for the development of [stand-alone games].

Google Suggest

  • AJAX (Asynchronous JavaScript and XML), first appeared in 2005 Google Suggest
  • It is not a “formal” technology like HTML, JavaScript, or CSS
  • It is in the browser side network programming (send a request, receive a response) technical solution
  • It lets you get the latest content directly from the server via JavaScript without having to reload the page
  • To bring the Web closer to the user experience of desktop applications

AJAX

  • AJAX is a set of apis provided by a browser that can be called through JavaScript to control the request and response through code. Implement network programming through JavaScript.
  • XML: The earliest data format used to pass data between the client and the server.

Application scenarios

  • Obtain data on demand
  • Verify user data
  • Automatically update page content
  • Improves the user experience without refreshing the experience

Experience the ajax

  • Using Ajax encapsulated in jQuery, fast experience brings.
  • Free interface: jsonplaceholder.typicode.com/

Native AJAX

Send ajax request step

  • 1. Create an object of type XMLHttpRequest
  • 2. Ready to send, open a link with a web address
  • 3. Perform the send action
  • 4. Specify the XHR status change event handler

Object of type XMLHttpRequest

  • At the heart of the AJAX API is an XMLHttpRequest type, which is used for all AJAX operations.

compatibility

  • var xhr = new XMLHttpRequest();
  • XHR = new ActiveXObject(“Microsoft.XMLHTTP”);
  • Code demo
//1. Obtain an object of type XMLHttpRequest
// Compatibility issues
var xhr;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else {
    / / IE6 compatible
    xhr = ActiveXObject("Microsoft.XMLHTTP");
}
Copy the code

The open method opens the request

  • XMLHttpRequest is essentially JavaScript’s way of sending AN HTTP request on the Web platform, so the request that goes out is still an HTTP request, again in an HTTP convention format.

Grammar: XHR. Open (method, url);

  • Method: Indicates the HTTP method to be used.
    • For example, [GET](GET data), [POST](submit new data), [PUT](make changes in data), [DELETE](DELETE data), and so on.
  • Url: The URL address to which the request is to be sent. The format is a string.
  • Code demo
// 2. Open the connection
// Get mode: you can append information to the address
// In post mode, data must be transmitted through the send method
xhr.open("get"."https://jsonplaceholder.typicode.com/users?id=1");
xhr.open("post"."https://jsonplaceholder.typicode.com/users");
Copy the code

The setRequestHeader() method sets the request header

  • This method must be called between the open() method and send()

Grammar: XHR. SetRequestHeader (header, value)

  • Header: Generally set “content-type “, the Type of data that the server wants us to transfer.
  • Value: specific data type, such as “Application /x-www-form-urlencoded” and” Application /json”.
  • Code demo
// Set the response header
// Get does not need to be set, but POST must be set
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
Copy the code

The send method and the request header

  • Used to send HTTP requests

Grammar: XHR. Send (the body)

  • Body: The body of data to be sent in an XHR request, with parameters passed based on the type in the request header.
  • If it is a GET method, there is no need to set the body. You can pass null or no parameters.
  • Code demo
// 3. Execute the send action
/ / the get method
// xhr.send(null);
/ / post way
xhr.send("name=mh&age=18");
Copy the code

ReadyState attribute

  • The readyState property returns the current state of the XMLHttpRequest agent. Since the ReadyStatechange event is triggered when the XHR object state changes (not just when the response is received), this means that the event will be triggered multiple times.
  • As is shown in

  • Code demo
//1. Obtain an object of type XMLHttpRequest
// Compatibility issues
var xhr;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else {
    / / IE6 compatible
    xhr = ActiveXObject("Microsoft.XMLHTTP");
}
/ / initialization
console.log("UNSEND",xhr.readyState);

// 2. Open the connection
xhr.open("post"."https://jsonplaceholder.typicode.com/users");
// Create a connection
console.log("OPENED",xhr.readyState);

// Set the response header
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");

// 3. Execute the send action
/ / post way
xhr.send("name=mh&age=18");

// 4. Specify the XHR state change event handler
xhr.onreadystatechange = function (){
    if(this.readyState === 2) {// The response header is received
       console.log("HEADERS_RECEIVED",xhr.readyState);
    }else if(this.readyState === 3) {// The response body is being loaded
       console.log("LOADING",xhr.readyState);
    }else if(this.readyState === 4) {// The load is complete
        console.log("DONE",xhr.readyState); }}Copy the code

Event handler

  • Typically, the subsequent logic of the response is executed when the readyState value is 4.
  • Code demo
// 4. Specify the XHR state change event handler
xhr.onreadystatechange = function (){
    if(this.readyState === 4) {console.log(this.responseText); }}Copy the code

Synchronous and Asynchronous

Display scene understanding

  • Synchronization: a person can only do one thing at a time, while performing some time-consuming operations (unsupervised) to do nothing else, just wait.
  • Asynchrony: Perform some time-consuming operation (unattended) to do something else instead of waiting.

Implementation in Ajax

  • The third argument to the xhr.open() method asks for a Boolean value that sets whether the request will be executed asynchronously.
  • Default: true asynchronous. You can pass false if you want to execute synchronously.
  • In synchronous execution, the code will be stuck in the xhr.send() step until all data has been transferred.

advice

  • Question: Why is the onReadyStatechange event not triggered when synchronizing
    • The: onReadyStatechange event is triggered only when readyState changes. When synchronization is executed and all data is transferred, the readyState will not change and the event will not be triggered.
    • Solution: To make the event more reliable, register the onReadyStatechange event before sending the request send().
  • Code demonstration (whether synchronous or asynchronous can trigger success)
 //1. Obtain an object of type XMLHttpRequest
// Compatibility issues
var xhr;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else {
    / / IE6 compatible
    xhr = ActiveXObject("Microsoft.XMLHTTP");
}

// 2. Open the connection
// Execute asynchronously
// xhr.open("post","https://jsonplaceholder.typicode.com/users",true);
// Execute synchronously
xhr.open("post"."https://jsonplaceholder.typicode.com/users".false);

// Set the response header
// Get does not need to be set, but POST must be set
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");

// 4. Specify the XHR state change event handler
xhr.onreadystatechange = function (){
    if(this.readyState === 4) {// The load is complete
        console.log("DONE",xhr.readyState); }}// 3. Execute the send action
/ / post way
xhr.send("name=mh&age=18");

// The code behind Ajax
console.log("after ajax");
Copy the code
  • Understand the synchronization mode, but don’t use it.

Response data format

Ask questions

  • What if you want the server to return complex data?
  • Questions of interest: what format is the data emitted by the server and how is this format parsed by the client using JavaScript.

XML

  • A means of describing data
  • Reasons for elimination:
    • There is too much data redundancy. Metadata (the data used to describe data) occupies a large amount of data, which is not conducive to the network transmission of large amounts of data.
    • In other languages, such as JS parsing internal data, the method is more complex, not convenient to use.
  • Code demo

      
<booklist>
    <book>
       <name>The romance of The Three Kingdoms</name>
       <author>Luo guanzhong</author>
       <cate>classic</cate>
    </book>
    <book>
       <name>Journey to the west</name>
       <author>Wu chengen</author>
       <cate>classic</cate>
    </book>
    <book>
       <name>A dream of red mansions</name>
       <author>Cao xueqin</author>
       <cate>classic</cate>
    </book>
</booklist>
Copy the code

JSON

  • JavaScript Object Notation Object Notation
  • It is also a data description, similar to JavaScript literals
  • The server returns the value in JSON format, and the client parses the data in JSON format

The difference between JSON data and object literals

  • 1.JSON data does not need to be stored in variables
  • 2. You don’t need a semicolon at the end
  • 3. Attribute names in JSON data must be in quotes
  • Demo code
// Object literal
var obj = {
    name:"mw".age:45.brother: {name:"lh".age:36}};Copy the code
// The data is in json format
{
    "name":"zs"."age":18."hobby": ["paino"."paint"]}Copy the code

ES5 Added a JSON object

  • Parse method for JSON objects
    • Parameter: string (in JSON format)
    • Return value: converted to an object
  • The stringify method of a JSON object
    • Parameter: object
    • Return value: string (in JSON format)
  • Demo code
// Object literal
var obj = {
    name:"mw".age:45.brother: {name:"lh".age:36}};// Create a string that matches the JSON data format
var str = '{"name":"ff","age":99}';
// New JSON object in ES5
// The parse and stringify methods of the JSON object
/ / 1. Stringify method
// Convert object literals to strings
console.log(JSON.stringify(obj));
// Convert a string in the JSON data format to an object
var s = JSON.parse(str);
console.log(s);
// Attributes can be invoked by dotting
console.log(s.name); // ff
console.log(s.age);  / / 99
Copy the code

Pay attention to

  • Just because JSON and XML are used in AJAX requests does not mean they are necessarily related to AJAX, they are just data protocols.
  • Whether the server uses XML or JSON, the data is essentially returned to the client.
  • The server should set a reasonable content-type based on the format of the response Content.

JSON Server

  • Usually write some data, through Ajax to get. Therefore, you need to set up a temporary server locally.
  • Json-server is a Node module that runs the Express server and can specify a JSON file as the DATA source for the API.
  • You can quickly set up a Web server using jSON-server.
  • Address: github.com/typicode/js…

Native AJAX usage

How to write a JSON file

  • The attribute name in the JSON file, which then becomes the route name.

On the command line

  • Enter a specific folder: Enter CD, do not press Enter, and then enter the desired folder path, you can enter the folder. (Make sure the path is correct when hosting JSON files to the json-server server)
  • Otherwise, if the file cannot be found, the server will automatically create a JSON file with the same name.
  • The following figure

A GET request

  • Usually in the first GET request, arguments are passed through the ‘? ‘parameter passed.
  • In a GET request, you do not need to set the request header.
  • You do not need to set the response body. You can pass null or none

Example: Make a GET request to a JSON file deployed on the server

  • Return: data that meets the requirements
// Create an XHR object
var xhr = window.XMLHttpRequest 
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");

// Open the link
// xhr.open(method,url);
/ / get request
// Pass the parameter, filter to get
xhr.open("get"."http://localhost:3000/users? age=15");
// Execute send
xhr.send(null);

// Specify the XHR state change event handler
xhr.onreadystatechange = function (){
    if(this.readyState === 4) {console.log(this.responseText); }}Copy the code

A POST request

  • In the process of POST request, the request body is used to carry the data to be submitted.
  • You need to set the Content-type in the request header so that the server can receive data easily.
  • The data that needs to be submitted to the server can be passed through the parameters of the send method.

Example: Make a POST request to a JSON file that you have deployed on the server

  • Return: newly added data, and view the JSON file has successfully added data, id automatically increased.
// Create an XHR object
var xhr = window.XMLHttpRequest 
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
        
// Open the link
// xhr.open(method,url);
/ / post request
xhr.open("post"."http://localhost:3000/users");

// For a post request, the request header must be set
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
// Execute send
xhr.send('name=bb&age=23&class=2');

// Specify the XHR state change event handler
xhr.onreadystatechange = function (){
    if(this.readyState === 4) {console.log(this.responseText); }}Copy the code
  • Three ways to write a value when the send() method is passed
  • Code demo
// The first method
// For a post request, the request header must be set
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
// Execute send
xhr.send('name=bb&age=23&class=2');

// The second method
xhr.setRequestHeader("Content-Type"."application/json");
// Json data format
xhr.send('{"name":"bn","age":23,"class":1}');

// The third way
xhr.setRequestHeader("Content-Type"."application/json");
// Convert the object to a string
xhr.send(JSON.stringify({
    name:"nn".age:12.class:2
}));
Copy the code

Handle response data rendering

  • After receiving the requested data, the client needs to present the data to the interface.
  • Simple data structure: it can be processed directly by string operation (concatenation). When the data is too complex, string concatenation is not recommended because the maintenance cost of string concatenation is too high.
  • Complex data structure: It is recommended to use the template engine or the template string provided by ES6.
  • Code demo
* {
    margin: 0;
    padding: 0;
}
table {
    width: 300px;
    /* About 30 up and down in the middle */
    margin: 30px auto;
    font: 14px/28px Microsoft Yahei;
    color: # 333;
    /* Remove gaps between borders */
    border-collapse: collapse;
    /* border: 1px solid #666; * /
}
td.th {
    width: 100px;
}
Copy the code
<! In the table, tr represents a row, th represents the table header, td represents each cell where th and TD must be in tr
    <table border = "1" class ="box"> 
        <tr>
            <th>Student id</th>
            <th>The name</th>
            <th>The class</th>
            <th>age</th>
        </tr>
    </table>
    <script src="js/jquery.min.js"></script>
    <script>
        // Get the element
        // var $box = $(".box");
        var box = document.getElementsByClassName("box") [0];

        // Create an XHR object
        var xhr = window.XMLHttpRequest 
        ? new XMLHttpRequest()
        : new ActiveXObject("Microsoft.XMLHTTP");
        
        // Open the link
        xhr.open("get"."http://localhost:3000/users");
        // Execute send
        xhr.send(null);

        // Specify the XHR state change event handler
        xhr.onreadystatechange = function (){
            if(this.readyState === 4) {Arrays are objects
                // console.log(this.responseText);
                // Render the returned structure to the table
                var data = JSON.parse(xhr.responseText);
                console.log(data);
                var str = "";
                for(var i = 0; i < data.length; i++){
                    // 1. Concatenation string (for: simple data structures)
                    str += '<tr><td>'+ data[i].id +'</td><td>'+ data[i].name +'</td><td>'+ data[i].class +'</td><td>'+ data[i].age +'</td></tr>';
                    // 2. Complex data structure: it is recommended to use ** template engine ** or **ES6 provided template string **
                    // The template string recommended by ES6 can contain Spaces
                    str += `<tr>
                        <td>${data[i].id}</td>
                        <td>${data[i].name}</td>
                        <td>${data[i].class}</td>
                        <td>${data[i].age}</td>
                        </tr>`;
                }
                // console.log("hi");box.innerHTML += str; }}</script>
Copy the code

Encapsulation AJAX libraries

Encapsulate an Ajax function

  • Mainly to understand the process of encapsulation, it is common to use AJAX libraries provided by third parties in development because they can be more rigorous.
  • In order to make it easier to use the API in the later development process, the common practice is to wrap it into a function that can be called.
  • Code demo (extract the wrapped function into a separate file)
<script>
        // Wrap your own Ajax functions
        /* Parameter 1: {string} method Request method parameter 2: {string} URL request address parameter 2: {Object} params request parameter 3: {function} done Callback function to execute after the request is completed */
       function ajax(method,url,params,done){
            // Create an XHR object
            var xhr = window.XMLHttpRequest 
            ? new XMLHttpRequest()
            : new ActiveXObject("Microsoft.XMLHTTP");

            // Convert method to uppercase
            method = method.toUpperCase();
            // Parameter splicing
            var pair = [];
            for(var k in params){
                pair.push(k + "=" + params[k]);
            }
            var str = pair.join("&");
            // Determine the request method
            if(method === "GET") {// String concatenation or template string
                url += "?" + str;
            }
            xhr.open(method,url);

            var data = null;
            if(method === "POST") {// Request headers are required
                xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
                data = str;
            }
            xhr.send(data);

            // Specify the XHR state change event handler
            // Execute the callback function
            xhr.onreadystatechange = function (){
                if(this.readyState === 4) {// An object should be returned so that the client can render it better
                    done(JSON.parse(xhr.responseText)); }}}// Call the Ajax function you wrote
    ajax("get"."http://localhost:3000/users", {name:"zs".age:45
    },function (a){
        console.log(a);
    });
</script>
Copy the code
  • As the figure shows, all you need to do is reference