The working principle of ajax and the encapsulation method of asynchronous request
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!