Ajax based
Problems existing in traditional websites:
- In the case of a slow network speed, the page takes a long time to load, and users have to wait, resulting in poor user experience
- After the form is submitted, if one item fails to meet the requirements, the page hopping will clear the filled content and you need to fill in all the forms again
- If a page is reloaded when the contents in the header and bottom of the page are the same, resources are wasted and users wait longer
Ajax is a set of methods provided by the browser, which can realize the page without updating data, and improve the user experience of browsing web applications. (To achieve users to partially update the page of other data in the process of browsing the website) Function: used to achieve asynchronous interaction with the server function core: At the heart of AJAX is the JavaScript object XMLHttpRequest, first introduced in IE 5, which allows users to make requests to the server through JavaScript and process the response without blocking them
Ajax application scenarios:
- Pull up to load more data (Users slide up as they browse the site, and when they slide to the bottom of the page, click Load More to refresh the data on the page
- No refresh page for list data (only list data changes when data is switched from page 1 to page 2, other data in the site stays the same)
- Form items out of focus data validation (validation of form data, such as the uniqueness of a mailbox address)
- Search text drop down list (search text automatically prompts)
Ajax runtime environment:
To be effective, Ajax technology needs to run in a web site environment, using the server created by Node as the web server and implementing static resource access services
Ajax operation principle and implementation
Ajax acts as a proxy for the browser to send requests and receive responses to improve the user experience by partially updating the page data without affecting the user’s ability to browse the page.
In traditional browsers, the developer has no control over the receiving of requests and responses. In Ajax implementations, the developer has control over the receiving of requests and responses.
The XMLHttpRequest object
Ajax implementation steps
Ajax execution flow
- Create Ajax objects (that is, create proxies for the browser to help it send requests)
var xhr = new XMLHttpRequest(); Creating an instance object of the XMLHttpRequest constructor is creating an Ajax object
Copy the code
- Tell Ajax where the request is made and how
xhr.open('get'.'http://www.example.com'); // First argument: request mode, get, post second argument: request address
Copy the code
- Send the request
xhr.send();
Copy the code
- Get the response data from the server to the client (because the request is affected by the network speed, the time is not fixed, so you cannot directly get the result of the request after the send event, you need to add the event handler function under the object onload event, when the server responds to the client, The browser will automatically call the event handler corresponding to the onload event in the object, where it can get the data from the server to the client.)
xhr.onload = function () {
console.log(xhr.responseText); // Get the data of the server's response to the client via the resposeText property under XHR
}
Copy the code
The data format of the server-side response – JSON
In a real project, the server-side will most likely take JSON objects as the format for the response data. When the client gets the response data, it concatenates the JSON data with the HTML string, and then displays the concatenated result on the page using DOM. In other words, the combination of JSON data and HTML is done by the client instead of the server. In the process of HTTP request and response, both request parameters and response contents, if they are object types, will eventually be converted into object strings for transmission.
JSON.parse() // Convert json strings to JSON objects
Copy the code
Request parameter passing
GET request mode
xhr.open('get'.'http://www.example.com?name=zhangsan&age=20');
Copy the code
<p><input type="text" id="username"/></p>
<p><input type="text" ud="age"></p>
<p><input type="button" value="Submit" id="btn"></p>
<script type="text/javascript">
// Get the button element
var btn = document.getElementById('btn');
// Get the name text box
var username = document.getElmentById('username')
// Get the age text box
var age = document.getElementById('age')
// Add a click event to the button
btn.onclick = function () {
// Create an Ajax object when the button is clicked
var xhr = new XMLHttpRequest();
// Gets the value entered by the user in the text box
var nameValue = username.value;
var ageValue = age.value;
Username =123&age=456
In traditional request parameters, this parameter is concatenated. In Ajax, this parameter is concatenated
var params = 'username' + nameValue + '&age=' + ageValue;
// Configure the Ajax object
xhr.open('get'.'http://localhost:3000/get? ' + params;) // The string concatenation for the request parameter is complete
// Send the request
xhr.send();
// Listen for the response from the server to the client, that is, get the data of the response from the server
xhr.onload = function() {
console.log(xhr.responseText)
}
}
</script>
Copy the code
The above is only the client to obtain the request case, you can check in the browser developer tool request parameter string [concatenated correctly, the status code will display 404
Server-side response code:
// Introduce the Express framework
const express = require('express');
// Path processing module
const path = require('path');
// Create web server
const app = express();
// Static resource access services
app.use(express.static(path.join(__dirname, 'public')));
app.get('/get'.(req, res) = > {
res.send(req.query); //req.query returns the value of the object from which the client passed the get request parameters
});
// Listen on the port
app.listen(3000);
// Console prompts output
console.log('Server started successfully');
Copy the code
POST request mode
Instead of placing the POST request parameters after the address bar, they are placed in the request body, which in the Ajax method is placed in the set method
The differences between GET and POST requests are as follows: In a POST request, the request parameter type, namely the content-Type attribute, must be set in the request packet
In Ajax, setRequestHeader is used to set the request message. The first parameter is the name of the message attribute, and the second parameter is the value of the message attribute
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded') xhr.send('name=zhangsan&age=20');
Copy the code
Format of request parameters (including JSON format)
- Application/X-www-form-urlencoded get requests can only be submitted this way
Attribute Name = Attribute Value Name = Zhangsan&age =20& sex = maleCopy the code
- application/json
{name: 'zhangsan'.age: '20'.sex: 'male'}
Copy the code
Specifying the content-Type attribute as application/ JSON in the request header tells the server that the current request parameter is in JSON format.
JSON.stringify() The stringify () method takes a JSON object as an argument. Convert a JSON object to a JSON string
Copy the code
Note: GET requests cannot submit JSON object data format, json request must be POST, and traditional web sites do not support JSON object data format form submission (traditional web sites default to X-www-form-urlencoded form submission).
【 Case 】 Request parameters in JSON format are passed to the server
// 1. Create ajax objects
var xhr = new XMLHttpRequest();
// 2. Tell Ajax objects where and how to send requests
// 1) Request mode 2) Request address
xhr.open('post'.'http://localhost:3000/json');
// Tell the server through the request header what format is the request parameter passed from the client to the server
xhr.setRequestHeader('Content-Type'.'application/json');
// json.stringify () converts a JSON object to a JSON string
// 3. Send request
xhr.send(JSON.stringify({name: 'lisi'.age:50})); // Request parameters must be passed as strings, so they must be rotated to JSON strings
// 4. Obtain the data that the server responds to the client
xhr.onload = function (){
console.log(xhr.responseText)
}
Copy the code
Get the response from the server
Ajax status code: Each step in the process of creating an Ajax object, configuring an Ajax object, sending the request, and receiving the server-side response data corresponds to a value called the Ajax status code.
xhr.readyState // Get the Ajax status code
Copy the code
Onreadystatechange event: An event provided by an Ajax object that is automatically triggered when the Ajax status code changes. The Ajax status code can be retrieved and judged in the event handler, and when the status code is 4, the server response data can be retrieved via xhr.responseText.
// When the Ajax status code changes
xhr.onreadystatechange = function () {
// Determine when the Ajax status code is 4
if (xhr.readyState == 4) {
// Get the response data k on the server side
console.log(xhr.responseText); }}Copy the code
The differences between the two methods of obtaining server responses: The onload event is recommended, the code is simple, does not need ajax status code judgment, and only calls once
Ajax error handling
- The network is normal and the server can receive the request, but the result returned by the server is not the expected result.
You can judge the status code returned by the server and process it separately. Xhr. status* Gets the HTTP status codeCopy the code
app.get('/error'.(req,res) = > {
res.status(400).send('not ok');
})
Copy the code
On the client page:
if (xhr.status === 400) {
alert('Request error')}Copy the code
- The server does not receive the request and returns the 404 status code.
Check if the requested address is incorrect.Copy the code
- The network is smooth, the server can receive the request, and the server returns 500 status code.
Server side error, find back-end programmer to communicate.Copy the code
- The network is interrupted, and the request cannot be sent to the server.
When the network is interrupted, the onError event below the XHR object will be triggered, and the error will be processed in the onError event handler function.Copy the code
xhr.onerror = function() {
alert('Network down, unable to send Ajax request')}Copy the code
Cache problems of Internet Explorer of earlier versions
Problem: In lower versions of IE ==, Ajax requests have a serious caching problem, meaning that only the first request is actually sent to the server without changing the address of the request, and all subsequent requests are fetched from the browser’s cache. Even if the data on the server is updated, the client still gets the old data in the cache. Solution: Add a request parameter after the request address to ensure that each request address request parameter value is not the same.
xhr.open('get'.'http://www.example.com?t=' + Math.random());
Copy the code
Ajax asynchronous programming
Synchronous and asynchronous
synchronous:
- A person can only do one thing at a time. Only when one thing is done can he do another thing.
- Implementation into the code is to execute the next line of code after the previous line of code is completed, that is, the code is executed line by line.
console.log('before');
console.log('after');
Copy the code
Asynchronous:
- When a person is halfway through doing one thing, he or she moves on to something else, and when the other things are done, he or she goes back to the unfinished work.
- When it comes to code, the asynchronous code takes time to execute, but the program does not wait for the completion of the asynchronous code before continuing to execute the subsequent code. Instead, the program directly executes the subsequent code, and then looks back to see if the asynchronous code returns the result after the completion of the subsequent code execution. If it has returned the result, The prepared callback function is called to process the result of asynchronous code execution.
- Sending requests using Ajax is asynchronous code
- In javascript, event handlers are also a type of callback function
console.log('before');
setTimeout(
() = > { console.log('last');
}, 2000);
console.log('after');
Copy the code