Ajax — Ajax

Time:2021-8-3

Ajax -- Ajax

1. What is Ajax

1.1 problems in traditional websites

  • When the network speed is slow, the page loading time is long, and users can only wait
  • After the form is submitted, if one item is unqualified, you need to fill in all the form contents again
  • Page Jump and reload the page, resulting in waste of resources and increasing user waiting time

1.2 what is Ajax

AjaxIt is a set of methods provided by the browser, which can update the data without refreshing the page, realize local update, and improve the user’s experience of browsing website applications

1.3 Ajax application scenarios

  1. Page pull to load more data
  2. No refresh paging for list data
  3. Image out of focus data verification
  4. Search prompt text drop-down list

Take an inappropriate Chestnut:

Like buying a house, we need to discuss all kinds of problems with the landlord’s father, but often the landlord is very busy and doesn’t have so much patience to solve all kinds of problems for us, such as loans. This leads to our slow progress in buying a house. It’s us who are worried

Then what shall I do? At this time, we need an intermediary. It is a connector between us and the landlord to help us transfer information and solve problems. It can also reduce some trivial things for the landlord’s father, which greatly improves our house buying efficiency and reduces the landlord’s workload

Therefore, the client is like our buyer, the server is like the landlord’s father, andAjaxIt’s an intermediary

In short,AjaxIt is a bridge between client and server

Previous traditional mode:

Ajax -- Ajax

The of this mode is to request all the contents of the page at one time. Its disadvantage is that it leads to too much pressure on the server, too long waiting time, poor experience and low browser performance

useAjaxpattern:

Ajax -- Ajax

Server side passAjaxSend resources to the client asynchronously in batches, and then request them when we need them. When we pull the page to the bottom, some picture information will be displayed again, which is executionAjaxrequest

Especially in some e-commerce websites, pictures and videos consume bandwidth and must be usedAjaxTo make requests for resources

2、AjaxBasics

Now we know,AjaxIt is an agent between the browser and the server. It refreshes the page locally without affecting the user’s browsing, so as to improve the website performance and user experience.

AjaxThe technology needs to run in the website environment to take effect. We need to build a local oneAjaxEnvironment, this article usesNodeCommon server as demo server

JS provides aXMLHTTPRequestObject to createAjaxAjaxThe principle is throughXMLHTTPRequestThe object server initiates an asynchronous request, obtains data from the server, and then updates the page by JS operating the DOM node

so to speak,XMLHTTPRequestThe object isAjaxCore of

2.1 XMLHTTPRequestobject

XMLHTTPRequestObject method

<img style=”zoom:80%;” />

Serial number method describe
1 abort() Cancel current response, this method takes the XMLHttpRequest objectreadStateThe status value is reset to 0; For example, this method can be called when the request takes a long time and the response is no longer necessary
2 getAllResponseHeaders() Returns the HTTP response header as an unresolved string
3 getResponseHeader() Returns the value of the specified HTTP response header
4 open() Initialize HTTP request parameters and setRequest modeURLSynchronous or asynchronous
5 send() Send HTTP request
6 setRequestHeader() Set or add an HTTP request to an open but unsent request

XMLHTTPRequestObject properties

Ajax -- Ajax

Serial number Property or event describe
1 readyStateattribute Ajax status codes are 0, 1, 2, 3 and 4 respectively
2 onreadystatechangeevent WhenreadyStateThis function is triggered when the status code changes
3 statusattribute The HTTP status code returned by the server, such as 200 and 404
4 statusTextattribute The status name corresponding to the status code is returned; For example; 200 means “OK” and 404 means “notfound”
5 responseXMLattribute The response to the request is parsed into XML and returned as a document object
6 responseTextattribute The response body received from the server is returned as a text string

readyStateStatus value

Ajax -- Ajax

2.2 AjaxImplementation steps

1. CreateAjaxobject

let xhr = new XMLHttpRequest();

2. SetAjaxRequest address and request method

xhr.open('GET', 'http://127.0.0.1:3000/getData')

open():

  • First parameter: request method,GETPOST….
  • Second parameter: the URL of the request
  • Third parameter:trueorfalsetrueRepresents an asynchronous request,falseIndicates a synchronization request(optional, ignore, default istrue

3. Send request

xhr.send()

4. Get the response data of the server

//When the Ajax status code changes
xhr.onreadystatechange = function() {
    //When the Ajax status code is 4 and the server responds normally
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);  //  Get response body
    }
}

Of course, only asynchrony needs to detect the status code so cumbersome; If it is a synchronization request, you can directly receive the response returned by the server, because the script willsend()Then stop and wait for a response from the server

Server

useexpressCreate server

//Introducing express framework
const express = require("express");

//Create server
const app = express()

app.get('/getData', function(req, res) {
    //Solve cross domain problems
    res.setHeader('Access-Control-Allow-Origin', '*')
    //Server side response data
    Res.send ('we have received ');
})

//Listening port
app.listen(3000, function() {
    Console.log ('server opened ');
})

3. How Ajax works

3.1 corresponding data format of the server

In most cases, the serverJSONObject as the response data format, and the client gets itJSONAfter data andhtmlSplice and display on the web page

stayhttpIn request and response, whether request parameters or response data, if it is an object type, it will be converted to object character conversion for transmission

  • JSON.parse(): converts a JSON string to a JSON object
  • JSON.Stringfy(): convert the value into a string. Usually, when the client wants to transmit data to the server, it firstJSONObject to string
let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        //Convert response data of string type to JSON object
        let responseText = JSON.parse(xhr.responseText)
        let str = "<h2>" + responseText.text + "</h2>"
        document.body.innerHTML = str;  //  Render to page
    }
}

xhr.open('GET', 'http://127.0.0.1:3000/getData')
xhr.send()

becauseonreadystatechangeIt detects the Ajax status code, soonreadystatechangeEvents must be placed inopen()before

3.2 request mode

open()The first parameter of the method is the HTTP request method. Commonly used areGETPOSTHEADAny method supported by the server can. According to the HTTP standard, the request method remains capitalized, otherwise some browsers may not be able to process the request

1、GETrequest

xhr.open('get', 'http://www.example.com?name=zxc&age=18');

The transmitted data shall be spliced as above

Chestnut: the browser sends data to the server, and the server responds

Browser side:

<p><input type="text" id="namer"></p>
<p><input type="text" id="song"></p>
<p>< button > button < / button ></p>
let btn = document.querySelector('button')
let namer = document.querySelector('#namer')
let song = document.querySelector('#song')
btn.onclick = function() {
    namer = namer.value;
    song = song.value;
    let params = 'namer=' + namer + '&song=' + song;
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let responseText = JSON.parse(xhr.responseText); // {" Namer: "Joker Xue", "song": "just good"}
            console.log(responseText);
        }
    }
    xhr.open('GET', 'http://127.0.0.1:3000/getData?' + params)
    xhr.send()
}

Server side:

app.get('/getData', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.send(req.query)
})
  • getRequest to usequeryProperty to receive data

2、POSTrequest

postThe request method is relatively simpleGETMore complicated

  • First, it needs to set the request header
  • Secondly, its data is spliced and transmitted tosend()method
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send('name=zxc&age=18')

be careful:

  • postThe requested needs to be usedbodyProperty to get the data sent by the browser
  • In addition, you need to import packages and set them so thatreqObjectbodyAttributes; Otherwise, the server cannot receive data
const bodyParser = require('body-parser');
//Configure the body parser
app.use( bodyParser.urlencoded({extended: true}) )

Chestnuts:

let btn = document.querySelector('button')
let namer = document.querySelector('#namer')
let song = document.querySelector('#song')

btn.addEventListener('click', function() {
    namer = namer.value;
    song = song.value;
    var params = 'namer=' + namer + '&song=' + song;
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText);
        }
    };
    xhr.open('post', 'http://localhost:3000/getData');
    //Set request header
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    //Send the parameters of the form to the server through send()
    xhr.send(params);
})

3.3 format of request parameters

The format of request parameters is set in the request header

xhr.setRequestHeader('Content-Type',  )

1. Format of post request

Format:application/x-www-form-urlencoded

name=zxc&age=18%sex=girl

2. JSON format

Format:application/json

//JSON object
{name: 'zxc', age: '18', sex: 'girl'}

Specify in the request headerContent-TypeThe value of the property isapplication/json, tell the server that the current request parameter format isjson

4. New compatibility issues

1、XMLHTTPRequestobject

XMLHTTPRequestObject has compatibility problems. It is used in lower versionsActiveXobject

Resolve compatibility issues:

var httpRequest
if (window.XMLHttpRequest) {
    // Mozilla、Safari、IE7+
    httpRequest = new XMLHttpRequest(0)
} else if (window.ActiveXObject) {
    //IE6 and before
    httpRequest = new ActiveXObject('Microsoft.XMLHTTP')
}

2、onreadystatechangeevent

onreadystatechangeandonloadDifferences between two or group server-side response modes:

Differential description Onload event onreadystatechangeevent
Is it compatible with lower versions incompatible compatible
Is Ajax status code required unwanted need
Number of calls once many times
  • onloadIt is called only once and is relatively simple. Generally, this can be used
  • onreadystatechangeThis can be used when compatibility needs to be considered

Summary:

  1. AjaxIt is a method between the browser and the server. It can be used to alleviate the excessive pressure of the server’s one-time request and realize local page update
  2. onreadystatechangeEvents written inopen()Before, monitor the wholeAjaxRequest process
  3. GETRequest andPOSTAll requests usesend()Send response data
  4. GETData requested to be sentqueryProperty, andPOSTRequest is usedbodyProperty acquisition
  5. be careful:POSTThe request needs to set the request header, and the server needs to configure the environment