“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”
Writing in the front
I think it is necessary to learn AJAX well. This article summarizes the past and present life of AJAX and its use
What is AJAX?
AJAX = Asynchronous JavaScript and XML. AJAX is also known as AJAX. Who’s calling me ð€£
AJAX is not a new programming language, but rather a new approach to using existing standards.
AJAX is the art of exchanging data with the server and updating parts of a web page without reloading the entire page.
The biggest impact of Ajax is that pages can request data without refreshing. In the past, the page form submitted data, and after the user clicked the “submit” button, the page was forced to refresh, which was a very unfriendly experience.
There are many examples of applications that use AJAX: Sina Weibo, Google Maps, Kaixin001, etc. The emergence of AJAX has greatly promoted the development of the front end, so let’s start to learn AJAX ~
The use of AJAX
2.1 Creating XHR objects
All modern browsers support the XMLHttpRequest object (IE5 and IE6 use ActiveXObject). XMLHttpRequest is used to exchange data with the server in the background. This means that parts of a page can be updated without reloading the entire page.
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have the XMLHttpRequest object built in.
let xmlhttp = new XMLHttpRequest()
Copy the code
Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
let xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
Copy the code
Handle compatibility issues:
let xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Copy the code
2.2 Sending a Request to the Server
Sending a request to the server uses the OPEN and send methods of the XMLHtttpRequest object
xmlhttp.open("GET"."test1.txt".true);
xmlhttp.send();
Copy the code
GET or POST?
GET is simpler and faster than POST, and works in most situations.
However, in the following cases, use a POST request:
- Unable to use cached file (update file or database on server)
- Send a large amount of data to the server (POST has no data limit)
- POST is more stable and reliable than GET when sending user input that contains unknown characters
2.3 Server Response
To get a response from the server, use the responseText property of the XMLHttpRequest object.
The responseText property returns the response as a string, so you can use it like this:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
Copy the code
2.4 the onreadystatechange event
When the request is sent to the server, we need to perform some response-based tasks.
Each time readyState changes, the OnReadyStatechange event is triggered.
The readyState property holds the state information for the XMLHttpRequest.
Here are the three important properties of the XMLHttpRequest object:
attribute | describe |
---|---|
onreadystatechange | Stores the function (or function name) that is called whenever the readyState property changes. |
readyState | Holds the state of the XMLHttpRequest. It goes from 0 to 4. – 0: The request is not initialized. 1: The server connection is established. 2: The request has been received |
status | 200: “OK”; 404: Page not found |
3. Write a simple AJAX script
This is one of the most common test points in the interview, and while you may not be able to use native AJAX in your job, you will be able to use wrapped AJAX, but it is essential that you understand the basics, and it should be part of every programmer’s repertoire
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}else{
console.log('404 NOT FOUND')
}
}
xhr.send()
Copy the code
The one above is the easiest, but we can also implement it with promises. See the version below: ð
function ajax(url) {
const p = new Promise((resolve, reject) = > {
let xhr = XMLHttpRequest()
xhr.open("GET", url, true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText)
} else {
reject(new Error("404 NOT FOUND"))
}
}
xhr.send()
})
return p
}
Copy the code
4. Modern AJAX usage
The use of native JS is still more tedious, the actual project suggests to use the library like jQuery, the wrapped Ajax request method is very easy to use, and solve the browser compatibility problem.
About AJAX in jQuery
How to use AJAX in jQuery
fetch API
Fetch is a new technology product developed at the front end.
The following is an excerpt from Mozilla: The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple, reasonable way to asynchronously fetch resources across the network.
This functionality was previously implemented using XMLHttpRequest. Fetch provides a better alternative that can easily be used by other technologies, such as Service Workers. Fetch also provides a single logical location to define other HTTP-related concepts, such as CORS and HTTP extensions.
A few things to note when using FETCH:
- When an HTTP status code is received that represents an error, a Promise returned from fetch() is not marked as reject, even if the HTTP response has a status code of 404 or 500. Instead, it marks the Promise state as resolve (but sets the OK attribute of the return value of Resolve to false), and only marks it as reject if the network fails or the request is blocked.
- By default, FETCH does not send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on the user session (to send cookies, the credentials option must be set).
An example of using FETCH to fetch data
fetch('http://example.com/movies.json')
.then(function(response) {
returnresponse.json(); }) .then(function(myJson) {
console.log(myJson); });Copy the code
Fetch represents a more advanced technical direction, but the compatibility is not very good at present, so it should be used carefully in the project.
axios
First things first: Axios is not a new technology.
First things first: Axios is not a new technology.
Axios is a Promise-based HTTP client for browsers and NodeJS. It’s essentially an encapsulation of native XHR, but it’s an implementation of Promise that complies with the latest ES specification and has the following features:
- Create XMLHttpRequests from the browser
- Create an HTTP request from Node.js
- Supporting Promise API
- Intercept requests and responses
- Transform request data and response data
- Cancel the request
- Automatically convert JSON data
- The client supports XSRF defense
The use of axios
// Create a request for the user with the given ID
axios.get('/user? ID=12345')
.then(function (response) {
console.log(response); })
.catch(function (error) {
console.log(error); });
// The same can be done for the above request
axios.get('/user', {
params: {
ID: 12345 } }) .
then(function (response) {
console.log(response); })
.catch(function (error) {
console.log(error); });
Copy the code
For more information on using Axios, please refer to the official Axios documentation
Browser support
Axios is designed for modern browsers, so older browsers are not supported.
Axios is popular because of its clean design, simple API, and support for browsers and Node. It integrates well with various front-end frameworks. It is therefore recommended that you use the AXIos library in your projects
The last
This article summarizes the use of AJAX and how to hand-write one. It also introduces the various ways to use AJAX. If this post helped you, please give it a like. I have other columns, welcome to read ~ Vue from give up to play with the beauty of CSS
Later further plan
- Asynchronous progression and event loops
- Grid layout principle and actual combat
- Could VW and VH layouts be the new trend?