preface

We often need to use Ajax requests in front-end program development. In this article we’ll look at the details of our Ajax request. Strive for understandable and transparent, let it become a weapon in our development. All of our examples here are based on versions of Internet Explorer 9 and above.

Introduction to the

Why ajax? Ajax’s full name is Asynchronous Javascript And XML And HTML. This means asynchronous JS, XML and HTML. Before the advent of Ajax technology, our web page can only be refreshed after requesting data from the back end, which means that the whole page needs to be reloaded, which will consume a lot of resources, and the display effect of the page is very bad. Ajax is designed to address one of these problems, as it is a technique for quickly creating dynamic pages that update portions of the page dynamically without reloading the entire page. This will greatly reduce our resource consumption and user waiting time.

We can learn from the above passage:

  1. Ajax is asynchronous and is used after the page is displayed when the backend requests new data.
  2. Ajax is partial web content updates without a global refresh.
  3. Ajax is a technology for wasting resources, not a new language.

So we can do this with Ajax. It is an asynchronous algorithm, used in the background to give the new data body to the original data display on the page. It’s not a new language. So Ajax technology can have a flow like this: request background data -> data filtering processing -> DOM to replace the display of page content.

XMLHttpRequest

  1. XMLHttpRequest: An object provided by all browsers and used primarily for communication on the server side.

XMLHttpRequest is inherited in XMLHttpRequestEventTarget and XMLHttpRequestEventTarget inheritance and EventTarget, So we know that XMLHttpRequest has its own event to listen for. And it supports not only HTTP, but also FTP and other request protocols.

Let’s talk about his attributes first:

  • ReadyState: A property that we’ll touch on more often in the future that represents the request status code, which can be divided into five states:

  • Response: Returns the body of the response, whose type is mainly controlled by responseType. The content can be obtained when the readyState is 4.

  • ResponseType: Specifies the type of the response body that is returned. The responseType can be set after the request object is called open and sent. If the response body type is set, the response will be null. There is also an InvalidAccessError when setting the return type for each synchronous request. Let’s look at the optional types:

  • ResponseText: Returns a DOMString property value. If the response is not text or “”, an InvalidAccessError will be reported.

  • ResponseUrl: Returns the serialized URL, if the URL has an anchor, then the content after # is deleted. If there is a redirect, the responseURL value is the final URL after multiple redirects.

  • Status: returns the numeric status code in the response, i.e. 200,404, and so on.

  • StatusText: description corresponding to status.

  • Timeout: Set the request timeout period. The units are milliseconds.

  • WithCredentials: A Boolean type indicating whether a qualification such as cookies, Authorization Headers, or TLS client certificates should be used to create a cross-site access-control request. Using the withCredentials attribute at the same site is invalid. In addition, this indicator can be used to indicate that cookies are ignored in the response. The default value is false.

Here’s how:

  • Abort () : Abort the request content, and its readyState is set to 0.
  • GetAllResponseHeaders () : Returns all response headers.
  • GetResponseHeaders (name) : Passes the header and returns the corresponding value.
  • Open (method, URL, [async], [user], [password]) : Activates a request. If it is invoked again, it acts like abort.
  • OverrideMimeType () : The method is to specify a MIME type to replace the type specified by the server, so that the data transmitted in the server response message is processed according to the specified MIME type. For example, forcing stream mode processing to be “text/ XML “is used, even if the server does not specify it in the response header. This method must be valid for the caller before the send method. This is used to set the value of the Content-Type.
  • Send (data) : Sends an HTTP request. The method accepts an optional parameter as the body of the request. If the request method is GET or HEAD, the request body should be set to NULL.
  • SetRequest () : is the way to set the HTTP request header. This method must be called between the open() method and send() method. If you assign to the same header more than once, only one header with multiple values will be generated. If the Accept attribute is not set, the send() value is the default for this attribute */*.

Finally, let’s take a look at what happened:

  • OnreadyStateChange: Listens for readyState changes and is automatically called when readyState changes.
  • Onabort: called when the terminal is currently requesting it.
  • Onerror: called when an error occurs.
  • Onload: called when the request completes successfully.
  • OnloadStart: called when the request starts.
  • OnloadEnd: called when the request ends in any state.
  • OnProgress: Called when the request has more data to receive.

Having said so much how it can be without a complete example, the code serves:

ajax: (method, URL) => {
    let request = new XMLHttpRequest();

    request.onreadystatechange = (e) => {
      if(request.readyState === request.UNSENT){
        console.log("I haven't called the open method yet.");
      }
      else ifReadyState === Request. OPENED){request.timeout = 2000 // Sets the request timeout period request.withCredentials =trueRequest. OverrideMimeType ('text/plain'Request.setrequestheader (header, value) sets the content of the request header. request.responseType ="text"
      }
      else if(request.readyState === request.HEADERS_RECEIVED){
        console.log("Response header has been obtained.")}else if(request.readyState === request.LOADING){
        console.log("Still reading return body contents")}else if(request.readyState === request.DONE){
        console.log(request.status)
        console.log(request.response)
        console.log(request.responseText)
        console.log(request.responseXML)
      }
    }

    request.onloadstart = (e) => {
      console.log("Loadstart triggered")
    }

    request.onload = (e) => {
      console.log(request.responseURL);
    }

    request.onloadend = (e) => {
      console.log("Loadend triggered")
    }

    request.onerror = (err) => {
      console.log(err);
    }

    request.onabort = (e) => {
      console.log('Request terminated');
    }

    request.ontimeout = () => {
      console.log('Request has timed out')
    }

    request.open(method, URL)
    request.send()
    return request;
}
Copy the code

We use mock.js to simulate the request.

The end of the

This parallel article station for Ajax to do a basic explanation, after the cross and problems and so on, we will be unified in the back of the cross-domain problems in the general program for learning summary, hope to learn together and progress, goodbye