This morning when I was sorting out my notes, I found something about Ajax a long time ago. Back then, jQuery’s $.ajax() was used. JQuery is now on its way out, so today we’ll talk about ajax in its native form.

Basic usage

First, a quick introduction to Ajax, Asynchronous JavaScript + XML. It’s not a language, it’s not a new technology, it’s just a new term that was coined in 2005, and similar techniques can be traced back to the end of the last century, and the first large-scale use of Ajax was Gmail. As we all know, the previous web submission data is submitted through the form, a submission to the global refresh, very annoying. Although this problem can be solved by using iframe later, it is always too tedious. Ajax solves this pain point by sending an asynchronous request to the server via the XMLHttpRequest object, retrieving the returned data, and then manipulating the DOM to render incremental updates to the user interface painlessly.

Let’s take a look at this code, this is a get request code example, I believe you should be more familiar with it! In fact, this is a shortened version of the code, but in version 3 of the Red Book, there is an extra step to select the value passed in the ActiveXObject for so-called browser compatibility (we are passing in microsoft.xmlhttp, but there are other options). This is too far away, now there is no much significance, just a sense of the old programmers before it is not easy ah. Browsers fight, programmers suffer.

function ajax(method, url, async = true){
  let xhr = null
  if(window.ActiveXObject){  // IE5 IE6 has this object, which is unique to Microsoft, now basically does not have these two browsers, can not be ignored
    xhr = new ActiveXObject('Microsoft.XMLHTTP')}else if(window.XMLHttpRequest){  // Almost all modern browsers have this
    xhr = new XMLHttpRequest()  // Instantiate an XMLHttpRequest
  }
  xhr.open(method ,url, async)  // The request has not been sent during startup
  xhr.onreadystatechange = function(){  // Listen for readyState changes
    if(xhr.readyState === 4) {if(xhr.status === 200) {console.log(xhr.responseText)
      }
    }
  }
  xhr.send(null)  // Send phase
}
ajax('get'.'http://jsonplaceholder.typicode.com/posts/1')
Copy the code

Here we request link is http://jsonplaceholder.typicode.com/posts/1, this is a Fake data Online interface (Fake Online REST API). Here’s an online tool for you, JsonPlaceholder, which has a lot of interfaces that allow you to access some fake data across domains. This is also very convenient for us to test what. It also supports a variety of request methods, in addition to the basic GET and POST, other things like PUT,PATCH, etc are also supported.

The open method has three parameters, the first parameter represents the request mode, the second parameter represents the request URL, generally when we request to own domain, write relative path, only when we request to access remote links write absolute path. The third parameter is whether or not it is asynchronous, which it usually is. Get requests can also take parameters, called queryString, which is a string concatenated in the URL. For example, in the url https://www.xxx.com?name=zhangsan&age=12,name=zhangsan&age=12 is the parameter carried by the request. The key-value pairs are represented by the form key=value. Each key-value pair is connected by an ampersand. The first key-value pair is preceded by a? There’s another method I’ll introduce here: encodeURIComponent(), which is a method that encodes parts of a URI. There are certain characters that cannot be included in a valid URL, such as Spaces. In this case, we can use this method to escape the space, will become %20. Let’s look at the following example:

let str = Dog 'https://www.xxx.com?name='
let str2 = `https://www.xxx.com?The ${encodeURIComponent('name')}=The ${encodeURIComponent('dog')}`
console.log(str2)  // https://www.xxx.com?name=%E7%8B%97%E5%AD%90
Copy the code

You can see that the Chinese characters for dog have been escaped.

The onReadyStatechange method listens for changes in readyState, which we’ll talk about a little bit below.

After the send method is called, the request is actually sent. The parameter in this method represents the data to be sent. If not, we need to fill in null, otherwise some browsers may error. Let’s send a POST request

function ajax(method, url, async = true){
  const xhr = new XMLHttpRequest() 
  const data = {
    title:'title1'.body:'body1'.userId:1
  }
  xhr.open(method ,url, async) 
  xhr.setRequestHeader('Content-Type'.'application/json; charset=utf-8')  // Set a request header
  xhr.onreadystatechange = function(){  // Listen for readyState changes
    if(xhr.readyState === 4) {console.log(xhr.responseText) 
    }
  }
  xhr.send(JSON.stringify(data))
}
ajax('post'.'http://jsonplaceholder.typicode.com/posts')
Copy the code

Why does the POST request have a header? To be honest, I’m not really sure. I think it has something to do with the server setup. I went to the relevant information, think the following statement is the most reliable. Because without this, there’s a good chance the server won’t get the information we’re sending. We set this to ensure that the server knows there are parameters in the entity.

ReadyState status value

This represents the status value of an Ajax request, which is the number of stages an Ajax passes through that will respond whether the access is successful or not. You can prove this by printing readyState in the onReadyStatechange event of the ajax function above, and changing the request link to an address that doesn’t exist.

  • 0 indicates that the request was initially in this state when it was uninitialized and the open() method has not yet been called
  • The open() method has been called at this point
  • 2 Send The send() method has been called
  • 3 Some data has been received in the request
  • 4 Request completion Data acceptance is complete

These several states we know about the line, do not have to forcibly memorize. Our primary concern is state 4, where the response body has been downloaded and we can retrieve the contents of the response body. ResponseText, which gets the response data as a string. There is also a responseXML that retrieves the response data in XML form, which I have not used before. I’m comparing sending a request to launching a rocket, where 0 is the pre-launch stage,1 is pushing the rocket out but not yet launching, and 2 is pressing the launch button, the rocket receives the launch order and takes off. Send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send: send Just as rocket launches go through these stages,ajax also goes through the above stages.

The HTTP status code

HTTP status codes are familiar to all of you. For example, the most common HTTP status code is 200, which means the request was successful,304 means the cache was used,404 means the requested resource does not exist, and 500 generally means the server error, etc. There are many HTTP status codes, but we usually use less than 10 estimates. Usually we can sum it up as follows:

  • 1xx Information response class
  • 2xx Successful response
  • 3 xx redirection
  • 4XX Client error
  • 5XX Server error

You can see all the details here.

The load event

One of the first events introduced by Firefox to replace readyStatechange because readyState has changed to 4.

xhr.onload = function(){
  console.log(xhr.readyState)  / / 4
  if(xhr.status === 200) {console.log(xhr.responseText)
  }
}
Copy the code

In addition to the LOAD event, many other events are implemented in XMLHttpRequest level 2. For details, see MDN.

CORS(Cross-domain Resource Sharing)

Cros-origin Resource Sharing, cross-domain Resource Sharing. Because of the browser’s same origin policy, one of the same origin policies is the XMLHttpRequest same Origin policy, which prohibits the use of XHR objects to make HTTP requests to server addresses of different sources. Generally, only resources of the same origin can be accessed. The same source means the same protocol, host name, and port.

For the introduction of CORS, the Little Red Book says so. It is a W3C standard that defines how browsers and servers should communicate when they must access cross-domain resources. The basic idea behind this is to use custom HTTP headers to let the browser communicate with the server to determine whether a request or response should succeed or fail.

The traditional solution of cross-domain request is basically JSONP and IFrame. But now to Allow cross-domain Access, we generally need to set access-Control-allow-Origin, which is a strategy defined in HTML5 to solve resource cross-domain. Requires both browser and server support. Such as Access – Control – Allow – Origin: *, the * all domain can Access, if only Allow Access to a particular domain, is set as follows: Access-Control-Allow-Origin:http://www.xxx.com, said only HTTP :// the server at www.xxx.com can be accessed normally. For other domains that do not have this id, a message is displayed indicating that the server cannot be accessed. The browser allows cross-domain Access only after the access-Control-Allow-Origin header is added to the resource returned by the server. So let’s look at the response header that jsonPlaceholder returns

proxyTable

conclusion

It’s hard to see anyone using native Ajax in their projects anymore. Most people still use jQuery or Axios or whatever. We’re going to talk about native Ajax today, just to solidify the knowledge. What I said above, I believe you should have learned, but as time goes by, you may forget, so today we just review. The so-called review of the old to know the new, can be a teacher.