preface
Summary: This article explains the history of Ajax, working principles and advantages and disadvantages, the XMLHttpRequest object is explained in detail, and the use of native JS to implement an Ajax object to facilitate daily use.
- Damonare ajax library: Damonare ajax library
- Do you really know Ajax?
- Zhihu Column && Jianshu Special Topic: Front-end Aggressor (Zhihu) && Front-end Aggressor (Jianshu)
- Blog address: Damonare’s personal blog
Since ancient times, great achievements have been achieved not only by extraordinary talents, but also by perseverance.
The body of the
It is believed that the daily work of every front-end programmer is unavoidable to coordinate with the back-end, which naturally can not avoid using Ajax. However, I believe that not many programmers, no matter using ajax method wrapped in jquery or using vue-Resource plug-in of VUE, have really studied Ajax deeply. We use it for the sake of using it, and we’re too spoiled to look at how it works because we can still make something without knowing it. According to the 80-20 rule, the most important things in any group are only a small part of it, about 20 percent, and the other 80 percent, though majority, are secondary. Because of this, if you want to get into the 20 percent, you have to learn more than the average person can learn, learn more than the average person can learn.
Okay, so let’s start with Ajax from the beginning.
Ajax profile
In the 1990s, almost all web sites were implemented by HTML pages, which servers reloaded for every user request. What is the form? For example, if you log in to your Weibo account on the browser, fill out the form, click the login button, and a “complete” HTTP request is triggered. The server finds out that your login password is incorrect, and immediately returns the page to you. In the user’s view, it is a reloading process. Poor user experience! And it wastes a lot of bandwidth because most of the HTML is the same on the first and second pages. The response time of the application depends on the response time of the server because each application communication needs to send a request to the server. This results in the user interface being much slower to respond than native applications.
It wasn’t until 2005 that Google pioneered The use of Ajax in its applications, such as Google Maps and Gmail, that the technology took off in earnest.
It is now widely used:
- Use XHTML+CSS to express information;
- Use JavaScript to operate DOM (Document Object Model) to run dynamic effects;
- Manipulate data using XML and XSLT;
- Asynchronous data exchange with web server using XMLHttpRequest or the new Fetch API;
- Note: AJAX is distinct from RIA technologies such as Flash, Silverlight, and Java applets.
How Ajax works
Ajax works by adding an intermediate layer (the Ajax engine) between the user and the server, making user actions and server responses asynchronous. Not all user requests are submitted to the server, like – some of the data validation (such as whether the user input data) and data processing (such as digital) to determine whether the user input data to the Ajax engine to do, only need to read the new data from the server to the Ajax engine to submit a request to the server. By handing this over to the Ajax engine, the user feels much smoother.
Ajax pros and cons
The advantages of Ajax
1. No data is updated.
The biggest advantage of AJAX is the ability to communicate maintenance data to the server without refreshing the entire page. This makes Web applications more responsive to user interactions and avoids sending unchanged information over the network, reducing user wait times and leading to a great user experience.
2. Communicate with the server asynchronously.
AJAX uses an asynchronous approach to communicate with the server without interrupting the user’s actions, which makes it more responsive. Optimized communication between Browser and Server, reduce unnecessary data transfer, time and reduce data traffic on the network.
3. Balance front-end and back-end load.
AJAX can transfer some of the previous server burden to the client, using the client’s idle capacity to deal with, reduce the burden of the server and bandwidth, saving space and broadband rental costs. The principle of AJAX is “data on demand”, which can minimize the burden of redundant requests and responses on the server and improve site performance.
4. Standards-based widely supported.
AJAX is based on standardized and widely supported technologies and does not require downloading browser plug-ins or applets, but requires the customer to allow JavaScript to execute on the browser. As Ajax has matured, libraries have emerged to simplify the way Ajax is used. Similarly, another programming aid has emerged to provide alternative functionality for users who do not support JavaScript.
5. Interface and application separation.
Ajax separates the interface from the application (or data from presentation) in the WEB, which facilitates collaboration, reduces WEB application errors caused by non-technical modifications to the page, improves efficiency, and makes it more suitable for today’s publishing systems.
Ajax shortcomings
1.AjAX kills Back and bookmarks, breaking the browser mechanics.
One of the main criticisms of using Ajax is that it can break the browser’s ability to back up and add bookmarks. In the case of a dynamically updated page, the user cannot go back to the previous page state because the browser can only remember static pages in history. The possible difference between a fully read page and one that has been dynamically modified is subtle; Users often want to be able to cancel their previous action by clicking the back button, but this is not possible in Ajax applications. However, developers have come up with various solutions to this problem. Most of HTML5’s previous approaches have been to recreate changes on the page by creating or using a hidden IFRAME when the user clicks the back button to access the history. (For example, when a user clicks back in Google Maps, it searches in a hidden IFRAME and then reflects the search results on Ajax elements to restore the application state to its current state).
One approach to the problem of not being able to bookmark or bookmark states prior to HTML5 was to use URL fragment identifiers (often referred to as anchors, the part of the URL after the #) to keep track, allowing the user to return to a specified application state. (Many browsers allow JavaScript to update the anchor dynamically, which enables Ajax applications to update the anchor as they update the display.) HTML5 will be able to manipulate the browsing history directly and store the state of a web page as a string, which will be hidden when a web page is bookmarked or bookmarked. Both methods can also solve the problem of not going back.
2.AJAX security issues.
AJAX technology brings users a good user experience but also brings new security threats to IT enterprises. AJAX technology is like establishing a direct channel for enterprise data. This leaves developers inadvertently exposing more data and server logic than ever before. Ajax logic can hide client-side security scanning techniques, allowing hackers to build new attacks from remote servers. Ajax is also vulnerable to known security vulnerabilities, such as cross-site footstep attacks, SQL injection attacks, and credentials-based security vulnerabilities.
3. Users need to be prompted because of network delay
When developing Ajax, network latencies — that is, the interval between a request from the user and a response from the server — need to be considered carefully. Not giving users a clear response, not having proper preread data, or improper handling of XMLHttpRequest can be frustrating. A common solution is to use a visual component to tell the user that the system is doing something in the background and reading data and content.
XMLhttpRequest is introduced
Ajax(Asynchronous JavaScript and XML) does not refer to a single technology, but rather makes organic use of a series of related technologies. Although the name contains XML, the data format can actually be replaced by JSON, further reducing the amount of data to what is known as AJAJ. In order to make HTTP requests to the server using JavaScript, you need an instance of a class that provides this functionality. That’s where XMLHttpRequest comes in. Such a class was first introduced in Internet Explorer as an ActiveX object called XMLHTTP. Mozilla, Safari, and other browsers then implement an XMLHttpRequest class that supports the methods and properties of Microsoft’s original ActiveX objects. Microsoft has also implemented XMLHttpRequest.
The XMLHttpRequest class is obviously the most important.
XMLhttpRequest properties
onreadystatechange
A JavaScript function object that is called when the readyState property changes. The callback function is called in the User Interface thread.
readyState
Status of the HTTP request. When an XMLHttpRequest is first created, the value of this attribute starts at 0 and increases to 4 until the full HTTP response is received.
Each of the five states has an associated informal name. The following table lists the states, names, and meanings:
state | The name of the | describe |
---|---|---|
0 | Uninitialized | Initialization status. The XMLHttpRequest object has been created or reset by the ABORT () method. |
1 | Open | The open() method is called, but the send() method is not. The request has not been sent yet. |
2 | Sent | The Send() method has been called and the HTTP request has been sent to the Web server. No response was received. |
3 | Receiving | All response headers have been received. The response body began receiving but did not complete. |
4 | Loaded | The HTTP response has been fully received. |
ReadyState is not decremented unless the abort() or open() methods are called during a request process. The onReadyStatechange event handle is triggered each time the value of this property is increased.
responseText
The body (excluding the header) of the response received by the server so far, or an empty string if no data has been received.
If readyState is less than 3, this property is an empty string. When readyState is 3, this property returns the portion of the response that has been received so far. If readyState is 4, this property holds the entire response body.
If the response contains a header that specifies a character encoding for the response body, that encoding is used. Otherwise, Unicode UTF-8 is assumed.
responseXML
The response to the request is parsed into XML and returned as a Document object.
status
The HTTP status code returned by the server, such as 200 for success and 404 for “Not Found” error. Reading this property when readyState is less than 3 results in an exception.
statusText
This property specifies the HTTP status code of the request with a name rather than a number. That is, when the status is 200 it is “OK” and when the status is 404 it is “Not Found”. As with the Status property, reading this property when readyState is less than 3 results in an exception.
XMLHttpRequest method
abort()
Cancels the current response, closes the connection and terminates any pending network activity.
This method resets the XMLHttpRequest object to a state of readyState 0 and cancels all pending network activity. For example, you can call this method if the request is taking too long and the response is no longer necessary.
getAllResponseHeaders()
Return the HTTP response header as an unparsed string.
This method returns NULL if readyState is less than 3. Otherwise, it returns the headers of all HTTP responses sent by the server. The header is returned as a single string, one header on a line. Each line is separated by a newline character “\r\n”.
getResponseHeader()
Returns the value of the specified HTTP response header. The argument is the name of the HTTP response header to return. The header name can be specified in any case, and the comparison to the response header is case insensitive.
The return value from this method is the value of the specified HTTP response header, or an empty string if no header was received or the readyState is less than 3. If more than one header with the specified name is received, the value of the header is concatenated and returned, separating the values of each header with a comma and a space.
open()
Initializes a request. This method is used in JavaScript code; If it is native code, use the openRequest()) method instead.
Note: Calling this method again after an already active request (a request that has already called the open() or openRequest() methods) is equivalent to calling abort ().
parameter
-
method
The HTTP method used for the request; For example, “GET”, “POST”, “PUT”, “DELETE”, etc. If the next argument is a non-HTTP (S) URL, it is ignored.
-
url
The URL to which this request is directed
-
async
An optional Boolean parameter, which defaults to true, indicating whether an asynchronous operation is performed. If false, the send() method does not return anything until it receives data from the server. If true, a notification transparent to the developer is sent to the relevant event listener. This value must be true, if the multipart attribute is true, otherwise an accident will occur.
-
user
User name, optional, is authorized. The default argument is an empty string.
-
password
Password, optional, is authorized to use; The default argument is an empty string.
send()
Send an HTTP request with the parameters passed to the open() method and the optional request body passed to that method.
setRequestHeader()
Set or add an HTTP request to an open but unsent request (set the request header).
parameter
-
header
The name of the request header to be assigned
-
value
Value assigned to the specified request header
Ajax native JS implementation
Here is Ajax written with native JS:
var ajax = {};
ajax.httpRequest = function () {
// Determine whether the XMLHttpRequest object is supported
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
// Compatible with Internet Explorer
var versions = [
"MSXML2. XmlHttp. 6.0"."MSXML2. XmlHttp. 5.0"."MSXML2. XmlHttp. 4.0"."MSXML2. XmlHttp. 3.0"."MSXML2. XmlHttp. 2.0"."Microsoft.XmlHttp"
];
// define local variable XHR to store IE ActiveXObject
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {
}
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
// Async by default
if (async= = =undefined) {
async = true;
}
var httpRequest = ajax.httpRequest();
// Initializes the HTTP request
httpRequest.open(method, url, async);
// onreadyStatechange function object
httpRequest.onreadystatechange = function () {
//readyState = 4, get the data from the server
if (httpRequest.readyState == 4) {
// Callback server response data
callback(httpRequest.responseText)
}
};
if (method == 'POST') {
// Assign a value to the specified HTTP request header
httpRequest.setRequestHeader('Content-type'.'application/x-www-form-urlencoded');
}
// Send an HTTP request
httpRequest.send(data);
};
// Implement the GET request
ajax.get = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + (query.length ? '? ' + query.join('&') : ' '), callback, 'GET'.null.async)};// Implement the POST request
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)};Copy the code
If you’re using jquery or Zepto in large part because of its Ajax compatibility, try this one: Damonare’s Ajax library, you can give it a star if you like.
Afterword.
Ajax technology for the whole web application significance is extraordinary, only this article to pay tribute to those who have struggled in the front line for the implementation of Ajax technology and the popularity of the work of the predecessors.
Refer to the article
- Remember the pros and cons of how Ajax works
- Ajax