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
- The page pulls to load more data
- No flush paging for list data
- Representation leaves the focus of data validation
- 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,Ajax
basis
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 XMLHTTPRequest
object
XMLHTTPRequest
Object 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 thereadState A 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 |
XMLHTTPRequest
Property of an object
The serial number | Attribute or event | describe |
---|---|---|
1 | readyState attribute |
AJAX status codes, 0, 1, 2, 3, 4 |
2 | onreadystatechange The event |
whenreadyState This function fires when the status code changes |
3 | status attribute |
The HTTP status code returned by the server, such as 200, 404 |
4 | statusText attribute |
Returns the state name corresponding to the status code; For example; 200 means “OK” and 404 means “NotFound” |
5 | responseXML attribute |
The response to the request, parsed into XML and returned as a Document object |
6 | responseText attribute |
The response body received from the server is returned as a text string |
readyState
The status value
2.2 Ajax
Implementation steps
1, create,Ajax
object
let xhr = new XMLHttpRequest();
2, set upAjax
Request 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:
true
或false
.true
Represents an asynchronous request,false
Representing 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 objectJSON.Stringfy()
: Converts a value to a string, usually before the client transfers data to the serverJSON
Object 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.GET
request
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)
})
get
Request to usequery
Property to receive data
2,POST
request
POST requests are a little more complicated than GET
- First it needs to set the request header
- Secondly, its data is stitched to the end
send()
methods
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send('name=zxc&age=18')
Note:
post
The need to use the requestbody
Property to get the data sent by the browser- Also need to introduce packages, set up, make
req
Add a new one above the objectbody
Properties; 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.XMLHTTPRequest
object
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,onreadystatechange
The event
The difference between onreadystatechange and onload in two server-side or group responses:
The difference between describing | The onload event | onreadystatechange The 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 |
onload
It’s only called once, and it’s relatively simple, so you can use this in generalonreadystatechange
This is used when compatibility is a concern
Conclusion:
Ajax
Is 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 updateonreadystatechange
Event is written in theopen()
Before, watch the whole thingAjax
Request processGET
The request andPOST
Both requests are usedsend()
Sending response dataGET
The data sent by the request is usedquery
Property, whilePOST
Request to usebody
Properties for- Note:
POST
The request needs to set the request header, and the environment needs to be configured on the server side