Get the App
SLTechnology News&Howtos  ›  Development  › 

The working principle of ajax and the encapsulation method of asynchronous request

Shulou Source: shulou.com Published: 2022-06-03 15:05:05 09月10日 Update

This article mainly explains "how ajax works and how to encapsulate asynchronous requests". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how ajax works and how to encapsulate asynchronous requests.

Ajax principle:

The client sends an asynchronous request through the browser's built-in object XMLHttpRequest. When the server returns a response, it will call the previously registered callback function. In the callback function, you can use javascript operation DOM to update the page. The asynchronous request will not block the operation of the client, so that the data can be updated if the page cannot be refreshed.

Encapsulation of asynchronous requests:

The copy code is as follows:

Var xhr=false

/ / step1: create a XMLHttpRequest object that is compatible with all versions of the browser

If (window.XMLHttpRequest) {/ / IE7+, Firefox, Chrome, Opera, Safari

Xhr = new XMLHttpRequest ()

} else {

If (window.ActiveXObject) {/ / IE browser

Xhr = new ActiveXObject ("Microsoft.XMLHTTP"); / / IE5+

}

}

/ / step2: set callback function

Xhr.onreadystatechange = myCallback

/ / step3: create an asynchronous request

Xhr.open ("method", "url", true)

/ / if post: to set the encoding method of the body data of the request message

Xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")

/ / step4: send an asynchronous request

Xhr.send (content); / / if it is get, content is null, if post,content is a "name = value" pair.

At this point, I believe you have a deeper understanding of "how ajax works and how to encapsulate asynchronous requests". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Principles methods encapsulation work functions browsers browsing code content customers objects data methods pages learning updating practical deeper interest echo Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Docker Apple macOS Shulou Information