This is the 6th original article of Big Ice 2021, work with Big Ice on the front end!! 💪


Writing in the front

A few days ago, a friend was asked by the interviewer to talk about the principle of Ajax. He said that his answer was not very good. I thought, what does Ajax work? Don’t you just send a request for data to render the page? With the idea that skepticism is truth seeking, I retraced the evolution of Ajax. It turns out that Ajax created the entire front-end ecosystem on its own. Without Ajax, I would be a Java programmer today, writing JSP pages

Put it this way: Without Ajax, there would be no front-end processing of rendering data, no local refresh, no dynamic rendering, no real-time interaction, no front and back end separation, more work on the back end… Today, almost all websites are inseparable from it ~

What is the Ajax

Wikipedia describes the history of Ajax:

In the 1990s, almost all web sites were implemented as HTML pages, with servers reloading pages to handle each user request. This approach is not efficient. The user experience is that all the pages will disappear and be reloaded. Even if only a part of the page elements change, the whole page will be reloaded, and not only the changed parts but also the unchanged parts should be refreshed. This can add to the burden on the server.

This can be solved with asynchronous loading. In 1995, the first version of the JAVA language was released, and with it JAVA Applets implemented asynchronous loading for the first time. Browsers exchange data with servers by running Java Applets embedded in web pages without refreshing web pages. 1996 Internet Explorer added the iframe element to HTML, enabling partial web page refresh.

Around 1998, the Outlook Web Access group wrote the first component, XMLHTTP, that allowed client scripts to send HTTP requests. This component was originally part of Microsoft Exchange Server and quickly became part of Internet Explorer 4.0[2]. Outlook Web Access is considered by some observers to be the first successful business application to use Ajax technology and the leader of many products, including Oddpost’s webmail products.

However, in early 2005, a number of events led to the adoption of Ajax. Google uses asynchronous communication in its famous interactive applications, such as Google discussion groups, Google Maps, Google Suggest, Gmail, and so on. The term Ajax was coined by an article called Ajax: A New Approach to Web Applications, which quickly spread and raised awareness of the use of the technology. In addition, Mozilla/Gecko support allows the technology to mature and become easier to use.

Ajax contains

Presentation based on XHTML and CSS standards; DOM (Document Object Model) is used for dynamic display and interaction; Use XMLHttpRequest to communicate with the server asynchronously; Use JavaScript to bind data.

  • Use XHTML+CSS to express information;
  • Using JavaScript to manipulate DOM (Document Object Model) to run dynamic effects;
  • Use XML and XSLT to manipulate data
  • Use XMLHttpRequest or the new Fetch API for asynchronous data exchange with the web server;

The principle of Ajax

The principle of Ajax is simply to use the XmlHttpRequest object to send asynchronous requests to the server. It is equivalent to adding a middle layer (Ajax engine) between the user and the server. The user’s actions are asynchronous and the server’s response is asynchronous. This process does not block user action or page rendering.

Of course, not all user requests will be sent to the server. Some data validation and processing will be done by the Ajax engine itself. Only when new data needs to be read from the server will the Ajax engine submit the request to the server on its behalf. When the data is obtained from the server, javascript is used to manipulate the DOM to update the page.

The most critical step in this is getting the request data from the server. To understand this process and how it works, we need to know something about XMLHttpRequest.

An asynchronous request

Asynchrony means doing one thing while doing another.

Synchronization means that you can’t move on to the next thing until you’ve done one thing.

Asynchronous request is the essence of Ajax, and XMLHttpRequest is the core mechanism of Ajax, it is first introduced in IE5, is a technology to support asynchronous request, XMLHttpRequest is an object of THE XMLHTTP component. Here are the methods and properties of this object:

XMLHttpRequest object method

The method of describe
abort() Stop the current request
getAllResponseHeaders() Return all response headers of the HTTP request as key/value pairs
getResponseHeader(“header”) Returns the string value of the specified header
open(“method”,”URL”,[asyncFlag],[“userName”],[“password”]) Establish calls to the server. The method parameter can be GET, POST, or PUT. The URL parameter can be a relative OR absolute URL. This method also includes three optional parameters, asynchronous or not, username, and password
send(content) Send a request to the server
setRequestHeader(“header”, “value”) Sets the specified header to the supplied value. You must call open() before setting any headers. Set the header and send it with the request (the ‘post’ method must be)

XMLHttpRequest object properties

Belong to sex describe
onreadystatechange A state change event trigger that fires each state change, usually calling a JavaScript function
readyState Status of the request. There are five possible values: 0 = uninitialized, 1 = Loading, 2 = loaded, 3 = interacting, 4 = finished
responseText The server responds by returning the data in text.
responseXML The server responds by returning data to a DOM-compliant XML document object, which can be parsed into a DOM object.
responseBody Topic returned by the server (not in text format)
responseStream The data flow returned by the server
status HTTP status code for the server (e.g. 404 =” End of file found “, 200 =” Success “, etc.)
statusText The status text information returned by the server, the corresponding text of the HTTP status code (OK or Not Found, etc.)

The use of Ajax

In the current front-end development process, Ajax has been repackaged by a framework or component so that we can use it without having to reinvent the wheel. However, it is necessary to be familiar with the basic principles of encapsulation, so that you can find the problem quickly and accurately when debugging

So the following ice cube to explain the Ajax packaging process in detail ~

A, createAjax object

// The XmlHttpRequest object is created in different browsers. The following methods are common across browsers:
var xmlHttp
if (typeofXMLHttpRequest ! ="undefined") {
    xmlHttp = new XMLHttpRequest()
} else if (window.ActiveXObject) {
    var aVersions = ["Msxml2. XMLHttp. 5.0"."Msxml2. XMLHttp. 4.0"."Msxml2. XMLHttp. 3.0"."Msxml2.XMLHttp"."Microsoft.XMLHttp"];
    for (var i = 0; i < aVersions.length; i++) {
        try {
            xmlHttp = new ActiveXObject(aVersions[i])
            break
        } catch (e) {}
    }
}
Copy the code

Second, callopensend

// Pass in the request mode, request address and whether asynchronous Boolean values
xhr.open('GET'.'./getNews'.true)
// Do not need to set the following encoding when using GET request:
// xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
xhr.send();
Copy the code

Three, listeningonreadystatechange The event

xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200) {// Convert the response data into JSON format for us to use.
     console.log(JSON.parse(xhr.responseText)) 
    }
}
Copy the code

According to the above instructions, we can wrap an Ajax to use, let’s try to wrap it

Four, encapsulate one yourselfAjax

function myAjax (options){
    this.method = options.method
    this.url = options.url
    this.data = options.data || ' '
    this.flag = options.flag || true
    this.callback = options.callback
    var self = this
    var xmlHttp
    if (typeofXMLHttpRequest ! ="undefined") {
        xmlHttp = new XMLHttpRequest()
    } else if (window.ActiveXObject) {
        var aVersions = ["Msxml2. XMLHttp. 5.0"."Msxml2. XMLHttp. 4.0"."Msxml2. XMLHttp. 3.0"."Msxml2.XMLHttp"."Microsoft.XMLHttp"];
        for (var i = 0; i < aVersions.length; i++) {
            try {
                xmlHttp = new ActiveXObject(aVersions[i])
                break
            } catch (e) {}
        }
    }
    if(this.method == 'GET' || this.method == 'get'){
        xmlHttp.open('GET'.this.url + "?" + this.data, this.flag)
        xmlHttp.send()
    }else{
        xmlHttp.open('POST'.this.url, this.flag)
        xmlHttp.setRequestHeader('Content-type'.'application/x-www-form-urlencoded')
        xmlHttp.send(this.data)
    }
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {if(self.method == 'GET' || self.method == 'get'){
                self.callback(JSON.parse(xmlHttp.responseText))
            }else{
                self.callback(xmlHttp.responseText)
            }
        }
    }
}
Copy the code

Pros and Cons of Ajax

  1. Update only data without refreshing the page Exchanging data with the server without refreshing the entire page. This makes Web applications more responsive to user interactions and avoids sending unaltered messages across the network, reducing user waiting times and resulting in a very good user experience.

  2. Asynchronous communication with the server Ajax communicates with the server in asynchronous mode without interrupting the user’s operations, thus providing faster response capabilities. Optimized communication between the browser and the server, reducing unnecessary data transmission, time and data traffic on the network.

  3. Front-end and back-end load balancing. Ajax can transfer some of the work previously carried out by the server to the client side, taking advantage of the idle capacity of the client side to handle, reducing the burden on the server and bandwidth, saving space and broadband rental costs. The principle of Ajax is “fetch data on demand”, which minimizes the burden of redundant requests and responses on the server and improves site performance.

  4. Safety issues arising. Ajax technology not only brings good user experience to users, but also brings new security threats to IT enterprises. Ajax technology is just like establishing a direct channel to enterprise data. This inadvertently exposes developers to more data and server logic than ever before. The Ajax logic can be hidden from client-side security scanning techniques, allowing hackers to set up new attacks from remote servers. Ajax is also not immune to known security vulnerabilities, such as cross-site footstep attacks, SQL injection attacks, and credential based security vulnerabilities.

  5. Architectural design issues

    The presentation layer, business logic, and data layer are placed on the server, the browser only User Interface engine (User Interface engine); This method is also called thin Client architecture, or server-centric architecture. This would be more appropriate for the end user, but the design and execution performance of JavaScript might not be sufficient to handle complex business logic.

    The presentation layer and the logical layer can be processed on the client side, because all the programs are executed in JavaScript on the client side, and only when the data is needed, the service is required from the server. This method is also called fat client architecture. Servers in this architecture are usually only used to provide and store data. This is relatively easy to do when developing an application, but the presentation layer is a fixed template style, which is expensive to change.

  6. Browser Compatibility

    Ajax is essentially a browser-side technology, and the inevitable first problem is browser compatibility. JavaScript/DOM/CSS support is always partially different or buggy from browser to browser, and even from browser to browser, JavaScript/DOM/CSS support may be partially different. This results in programmers writing Ajax applications spending more time debugging browser compatibility than in the application itself. Therefore, most Ajax link libraries or development frameworks today exist in the form of JS link libraries that define higher-order JavaScript apis, JavaScript objects (templates), or JavaScript Widgets to solve this problem. Such as the prototype. Js.

    But now that browser vendors are working on improving their browsers according to Web standards, W3C standards, etc., I believe that one day front-end development time will be spent not on compatibility, but on technology.

After recombing Ajax, I found a lot of unfamiliar points before, which is equivalent to relearning Ajax. The development and progress of technology are inseparable from the most basic knowledge. Although there are more and more frameworks and knowledge to learn at the front end, the most important thing is the most basic JavaScript. Although written about Ajax is pretty basic, but compared with the front end of the contact with their own, or feel more profound experience (the next interview can also be happy to blow ~😜), I hope you have the same feeling.

Write in the back

This is the fifth article in Big Ice’s “Read it and Understand it” series, which aims to present some common concepts or methods in an easy-to-understand way. Welcome to click on other articles to discuss and learn:

  • Promise me, we’ll start using Symbol when we’re done.
  • “Read to understand the series” talk about the principle and implementation of data buried point
  • Is it complicated to manage the rights in the project of “Read the Series”?
  • “You know it when You’re Done” Oh, my God! Throttling and shaking are so simple to understand
  • 15 ways to play with strings
  • Substr (), slice(), substring(

Originality is not easy, if there are mistakes, welcome to point out.

If it helps you, please give the ice cube a triple (like the collection comments), let’s progress on the road to the front together ~🤭