This is the third day of my participation in Gwen Challenge
Ajax
Asynchronous Javascript And XML
There are tons of Ajax blogs out there, and some of the ones I’ve written about have Ajax content
But Ajax is also the foundation of high-performance JavaScript, which can make pages load faster by delaying the download of bulky resource files.
Transfer data asynchronously between client and server, or even get an entire page of resources with a single HTTP request (definitely not a good idea)
The data transfer
Ajax is at its most basic level: a way to communicate with the server without reloading the page
The request data
Five common techniques are used to request data from the server:
- The XMLHttpRequest (XHR)
- Dynamic script Tag Insertion Dynamic script injection
- iframes
- Comet
- Multipart XHR
Currently, of course, only three are commonly used: XHR, dynamic script injection, and Multipart XHR
The XMLHttpRequest (XHR)
This is by far the most common technique, allowing data to be sent and received asynchronously
MDN introduction
This is the core of Ajax, and it is fully supported by all major browsers, which means that any browser that doesn’t support it is non-mainstream
Use examples:
let url = 'Interface name';
let params = ['id=123'.'name=456'] // Request parameters
const req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState === 4) { // Check whether the response status is successful
let responseHeaders = req.getAllResponseHeaders(); // Get the response header information
let data = req.responseText; // Get the response data
// Data processing}}// This is the get method &des=get method parameters are appended directly to the interface
req.open('GET',url + '? ' + params.join('&'), true);
req.setRequestHeader('X-Requested-with'.'XMLHttpRequest');// Set the request header information
req.send();// Send the request
Copy the code
The readyState value has five states (which are different from the status status code) :
- 0 – (uninitialized) The send() method has not been called
- 1 – (load) The send() method has been called and the request is being sent
- 2 – (load completed) The send() method is complete and all responses have been received
- 3 – (Interaction) Parsing the response content. Some information was received, but not all
- 4 – (Done) The response content is parsed and can be invoked on the client. All messages are received
The status code is an attribute of the XMLHttpRequest object that represents the HTTP status code of the response
For example: 404, often referred to as the light of harmony, actually means no file found or no page found in the URL
The difference between:
- ReadyState is a step that runs through several states of the request and responds regardless of access success
- Status refers to the HTTP header code returned by the server based on the submitted information, regardless of whether the access was successful or not
Because XHR provides advanced control, browsers have added some restrictions to their use of XHR
The most famous restriction is the same-origin policy, which cannot request data from outfields using XHR
As for the lower version of IE, not only does it not support “streaming”, but it also does not provide readyState 3. The data returned from the server is treated as a string or XML object, making processing large amounts of data slow. I think we can skip this point though, and here the lower version of IE means IE6 and below. If you’re working on a project that still needs to be compatible with these browsers, what’s the point
Note (mainly in terms of performance) :
- Whether you request data directly using XHR or Ajax, you need to choose between POST and GET
- If you do not need to change the server state, then it is recommended to use GET requests. The benefit of GET is that the request data is cached, which can help improve performance if you need to request the same data multiple times
- POST is a good way to get data when the URL plus parameters is longer than or near 2048 characters. The maximum length of the Internet Explorer URL is 2083 bytes, and the maximum length of the data that can be passed by GET is 2048 bytes
Dynamic script injection
The biggest benefit of this technique is the ability to make cross-domain requests compared to XHR.
Because this is a Hack, instead of instantiating an object, you can simply create a new script tag in JavaScript and set the SRC attribute to the URL of a different field.
let scriptElement = document.createElement('script');
scriptElement.src = 'path';
document.getElementsByClassName('head') [0].appendChild(scriptElement);
Copy the code
Most of you have seen this before, and one of the cross-domain solutions on the front end is the ability to cross-domain using script tags
You think this is the best way to get across domains?
- Compared to XHR, dynamic script injection has limited control, and parameter passing can only use GET rather than POST
- And you can’t set request timeout or retry, so you don’t know if the request fails
- There is no readyState and the data must all be returned before it can be accessed
- The header of the request cannot be accessed, nor can the entire response message be treated as a string
“The list of shortcomings is legion.
Note: Although flawed, this technique is very fast and the response messages are executed as JavaScript.
Be careful when introducing external JavaScript code. This technique can be dangerous when requesting data from a server you have no direct control over. JavaScript has no concept of permissions or access control.Who knows what you’re introducing
Multipart XHR
MXHR allows clients to transfer multiple resources from the server to the client with a single HTTP request.
Multipart XHR packages resources at the server into a long string split by mutually agreed strings and sends it to the client, where the long string is parsed and each resource is parsed based on the MIME-type and other information passed in
Is this actually a variant based on XHR?
Beacon (beacons)
This technique is similar to dynamic script injection
Create a new Image object using JavaScript and set the SRC property to the script URL on the server. The URL contains the key-value pair data that we want to return via GET. The beacon could not send a POST request
Note that the IMG element is not created or inserted into the DOM
var url = 'Interface name';
varParams = [data]var beacon = new Image();
beacon.src = url + '? ' + params.join('&');
// Use the load event to listen for the server to successfully receive data
// You can make different responses on the server side, such as returning a blank image of x width for successful reception and a blank image of Y width for failed reception
beacon.onload = function() {
if (this.width == x) {
/ / success
} else if (this.width == y){
// Failed. Please try again
}
}
beacon.onerror = function() {
// Error, try again later and create another beacon
}
Copy the code
Example: HTML page:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title> beacons </title>
</head>
<body>
<button onclick="beaconbtn()">beacon</button>
<script>
function beaconbtn() {
var url = 'http://localhost:3001/goodsList.png';
var params = ['id=123'.'name= empty city machine '.'data= Tests whether data can be received in the background '] // The data sent
var beacon = new Image();
beacon.src = url + '? ' + params.join('&');
// Use the load event to listen for the server to successfully receive data
// You can make different responses on the server side, such as returning a blank image of x width for successful reception and a blank image of Y width for failed reception
beacon.onload = function() {
console.log(this)
if (this.width == 1) {
/ / success
console.log("Server succeeded in obtaining data")}else {
// Failed. Please try again
console.log("Server failed to get data. Please try again.")
}
}
beacon.onerror = function() {
// Error, try again later and create another beacon}}</script>
</body>
</html>
Copy the code
Node.js server:
const fs = require('fs');
const path = require('path');
const url = require('url');
const express = require('express');
var app = express();
app.use('/'.function(req, res) {
// Resolve the requested file path
var pathname = url.parse(req.url).pathname;
console.log('Received a request requesting:' + pathname);
console.log('Server receives:')
console.log(req.query)
fs.readFile(pathname.substr(1), function(err, data) {
if (err) {
console.log(err)
} else {
res.end(data)
}
});
})
// The number of the server's local host
app.listen('3001'.function(){
console.log("Turned on... , run the HTTP: localhost: 3001 / beacons. HTML")})Copy the code
Data obtained by VS Code terminal:
HTML interface effect:
The data format
When considering data transfer technologies, you have to consider these factors: functionality, compatibility, performance, and direction (whether you send to the server or the server sends to you)
When it comes to data formats, the only criteria for comparison is speed, and no one data format is always better than another, but JSON is by far the most popular
XML
When Ajax first became popular, XML was the data format of choice (PS: JSON was not yet an official interchange format)
But COMPARED to other formats, XML is extremely verbose and difficult to parse for JavaScript programmers. Most importantly, XML parses much slower than other data formats, and XML has no place in high-performance Ajax
So I suggest not using this XML for projects that are not particularly old and keep the front end easy!!
JSON
Well, this is by far the most popular data format, and I don’t need to tell you that it’s probably used for most back and forth data exchanges
JSON is a lightweight and easily parsed data format written directly using JavaScript objects and arrays
JSON is the foundation of high-performance Ajax
Fun fact: Eval can be used in JavaScript to parse JSON strings, but using eval in code can be dangerous, especially when executing third-party JSON data that may contain malicious code. Use json.parse () whenever possible
HTML
This data format is similar to XML in that JavaScript can transform large data structures into simple HTML, but the server can process the entire HTML back to the client faster.
But there are obvious downsides to this technology. Data is more bloated and can be transferred slowly over the network
Custom format
The ideal data format should contain only the necessary structure, and you can define one yourself that simply concatenates data with delimiters
Jojo; data; hello world; the; people;new;
Copy the code
This method is the fastest and can be used to split strings. However, it is necessary to make sure that the characters to be split are set, otherwise segmentation errors may occur
Ajax Performance Guide
The fastest Ajax request is no request
There are two main ways to avoid sending unnecessary requests:
- On the server side, set the HTTP header to ensure that your response is cached by the browser
- On the client side, the retrieved information is stored locally to avoid further requests
The first technique is the easiest to use and maintain, while the second gives you the most control
Set HTTP headers
If you want the Ajax response to be cached by the browser, you must send the request using GET
You also need to send the correct HTTP header information in the response
Setting Expires is the easiest way to ensure that the browser caches Ajax responses
Local data store
This way is more manual
Data received from the server is saved locally, such as cookies or local storage
Here is no more introduction, you can refer to the following articles:
Cookie, Session, AJAX, JSON
Brief introduction to Cookie, sessionStorage and localStorage
section
Some guidelines help speed up Ajax:
- Reduce the number of requests by combining JavaScript and CSS files, or by using Multipart XHR once
- Shorten page load times and wait until the main content loads before using Ajax to fetch secondary files
- Ensure that code errors are not transmitted to the user and that the server handles them
- Use some of the more mature Ajax libraries, such as jquery.Ajax, or write your own code for the underlying Ajax methods
JPG: teach you how to use Ajax to interact (entry will see)!!