What is Ajax

1.1 Problems existing in traditional websites

  • When the network speed is slow, the page load time is long and the user can only wait
  • After the form is submitted, if one item fails, you need to fill out all the form contents again
  • Page jump, reload the page, resulting in a waste of resources, increase the user waiting time

1.2 What is Ajax

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

1.3 Application scenarios of Ajax

  1. The page pulls to load more data
  2. No flush paging for list data
  3. Representation leaves the focus of data validation
  4. Search for prompt text in the drop-down list

To cite a chestnut that is not quite appropriate:

Like buying a house, we need to discuss all kinds of problems with the owner’s father, but often the owner is very busy, and does not have so much patience to solve all kinds of problems for us, such as: loan. This leads to our slow progress in buying a house, it is we who are in a hurry

So what can we do? At this time, we need an intermediary, he is a connection between us and the owner of the building, to help us pass information, solve problems, but also the owner of the father to reduce some trivia, which greatly improve our efficiency of buying a house, but also reduce the workload of the owner of the building

So, the client is like the house buyer, the server is like the father of the house, and Ajax is the intermediary

Simply put, Ajax is a bridge between the client and server sides

Previous traditional models:

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

Using the Ajax pattern:

The server sends resources to the client asynchronously through Ajax in batches, and then requests them when we need them. When we browse the page and pull down to the bottom, some picture information will be displayed, which is the execution of Ajax request

Especially in some e-commerce sites, pictures and videos are very bandwidth consumption, must use Ajax to request resources

2,Ajaxbasis

Now we know that Ajax is an agent between the browser and the server, which can partially refresh the page and improve the performance and user experience of the website without affecting the user’s browsing.

Ajax technology needs to run in a website environment to be effective, so we need to build an Ajax environment locally. This article uses the Node common server as the demonstration server

JS provides an XMLHttpRequest object to create Ajax. The principle of Ajax is to make an asynchronous request through the XMLHttpRequest object server, fetch data from the server, and then use JS to manipulate the DOM node to update the page

Arguably, the XMLHttpRequest object is the heart of Ajax

2.1 XMLHTTPRequestobject

XMLHTTPRequestObject methods

<img src=”https://pic2.zhimg.com/80/v2-bfb70da89ce8fa707bc8654f88a7356b_720w.png” alt=”img” style=”zoom:80%;” />

The serial number methods describe
1 abort() Cancel current responseThis method puts the XMLHttpRequest object into thereadStateA state in which the state value is reset to 0; For example, this method can be called when the request has been in use for a long time and the response is no longer necessary
2 getAllResponseHeaders() Returns the HTTP response header as an unparsed string
3 getResponseHeader() Returns the value of the specified HTTP response header
4 open() Initialize HTTP request parameters and set themRequest way,URL,Synchronous or asynchronous
5 send() Sending HTTP Requests
6 setRequestHeader() Sets or adds an HTTP request to an open but not sent request

XMLHTTPRequestProperty of an object

The serial number Attribute or event describe
1 readyStateattribute AJAX status codes, 0, 1, 2, 3, 4
2 onreadystatechangeThe event whenreadyStateThis function fires when the status code changes
3 statusattribute The HTTP status code returned by the server, such as 200, 404
4 statusTextattribute Returns the state name corresponding to the status code; For example; 200 means “OK” and 404 means “NotFound”
5 responseXMLattribute The response to the request, parsed into XML and returned as a Document object
6 responseTextattribute The response body received from the server is returned as a text string

readyStateThe status value

2.2 AjaxImplementation steps

1, create,Ajaxobject

let xhr = new XMLHttpRequest();

2, set upAjaxRequest address and request method

XHR. Open (' GET 'and' http://127.0.0.1:3000/getData ')

open():

  • The first parameter: request mode,GET,POST.
  • The second parameter: the URL of the request
  • The third parameter:truefalse.trueRepresents an asynchronous request,falseRepresenting a synchronous request(Optional, ignore the default istrue)

3. Send the request

xhr.send()

4. Get the response data of the server

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

Of course, only asynchrony requires such tedious detection of status codes; If the request is synchronous, the response returned from the server is received directly, because the script stops after send() and waits for the response from the server

Server:

Create the server using Express

// introduce the express framework const express = require("express"); // create server const app = express() app.get('/getData', function(req, function) Res.setHeader ('Access-Control-Allow-Origin', '*') // Res.send (' We have received '); }) // listen to app.listen(3000, function() {console.log(' Server turned on '); })

3. How Ajax works

3.1 Corresponding data format of the server

In most cases, the server takes the JSON object as the response data format. After the client gets the JSON data, it splices it with HTML and displays it on the web page

In HTTP requests and responses, both request parameters and response data, if they are object types, are converted to object characters for transmission

  • JSON.parse(): Converts a JSON string to a JSON object
  • JSON.Stringfy(): Converts a value to a string, usually before the client transfers data to the serverJSONObject to a string
let xhr = new XMLHttpRequest(); Xhr.onreadystatechange = function() {if (xhr.readyState === 4 &&xhr.status === 200) {// Conversion the string response data to the JSON-object let responseText = JSON.parse(xhr.responseText) let str = "<h2>" + responseText.text + "</h2>" document.body.innerHTML = str; / / render the page}} XHR. Open XHR (' GET 'and' http://127.0.0.1:3000/getData '). The send ()

Since onreadystatechange detects Ajax status codes, the onreadystatechange event must precede open()

3.2 Request Mode

The first argument to the open() method is the HTTP request method. The common methods are GET, POST, HEAD, etc. Any method supported on the server side can be used. Keep the request method uppercase according to the HTTP standard, 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 sent data should be concatenated as above

Chestnut: The browser side 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 ":" memory ", "song" : "just right"} the console. The log (responseText); }} XHR. Open (' GET 'and' 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

POST requests are a little more complicated than GET

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

Note:

  • postThe need to use the requestbodyProperty to get the data sent by the browser
  • Also need to introduce packages, set up, makereqAdd a new one above the objectbodyProperties; Otherwise the server will not be able to receive the data
const bodyParser = require('body-parser'); // App.use (bodyParser. Urlencoded ({extended: true})); // App.use (bodyParser. Urlencoded ({extended: true}));

Chestnut:

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 header xhr.setRequestHeader('Content-Type', 'Application/X-WWW-form-urlencoded '); // Send the form parameters to server-side xhr.send(params) via send(); })

3.3 Format of request parameters

The format of the 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'}

The value of the Content-Type property specified in the request header is application/json, which tells the server that the current request parameter format is JSON

4. Compatible with new problems

1.XMLHTTPRequestobject

The XMLHttpRequest object has compatibility issues, and lower versions use ActiveXObject

Solve compatibility issues:

Var HttpRequest if (window.XMLHttpRequest) {// Mozilla, Safari, IE7+ HttpRequest = new XMLHttpRequest(0)} else if (window.ActiveXObject) {// IE6 and its preceding HttpRequest = new ActiveXObject(' Microsoft.XMLHttp ')}

2,onreadystatechangeThe event

The difference between onreadystatechange and onload in two server-side or group responses:

The difference between describing The onload event onreadystatechangeThe event
Compatible with lower versions Are not compatible Compatible with
Whether an Ajax status code is required Don’t need Need to be
Number of times called At a time Many times
  • onloadIt’s only called once, and it’s relatively simple, so you can use this in general
  • onreadystatechangeThis is used when compatibility is a concern

Conclusion:

  1. AjaxIs a method, between the browser and the server know, can be used to relieve the server a request pressure is too large, to achieve partial page update
  2. onreadystatechangeEvent is written in theopen()Before, watch the whole thingAjaxRequest process
  3. GETThe request andPOSTBoth requests are usedsend()Sending response data
  4. GETThe data sent by the request is usedqueryProperty, whilePOSTRequest to usebodyProperties for
  5. Note:POSTThe request needs to set the request header, and the environment needs to be configured on the server side