What is the principle of Ajax
AJAX (Async Javascript and XML) is asynchronous Javascript and XML
Is a web development technique for creating interactive web applications that exchange data with servers and update portions of web pages without reloading the entire web page
Ajax works simply by making an asynchronous request to the server via an XmlHttpRequest object, retrieving data from the server, and then using JavaScript to manipulate the DOM to update the page
The flow chart is as follows:
The principal wants to find the head teacher to report the work, entrusts the secretary to call the head teacher himself to do other things, until the secretary tells him the head teacher has arrived, finally the head teacher reports the work with the leadership
The data flow of the Ajax request is similar to that of “the principal wants to talk to the head teacher,” where the secretary is the XMLHttpRequest object, the principal is the browser, and the response data is the head teacher
The browser can send the HTTP request, then do something else, and wait until it receives the data back from XHR
Second, the implementation process
Implementing Ajax asynchronous interaction requires the server logic to work together and the following steps are required:
- Build the core Ajax object XMLHttpRequest object
- Establish a connection to the server through the open() method of the XMLHttpRequest object
- Build the data content required for the request and send it to the server side via the send() method of the XMLHttpRequest object
- The onReadyStatechange event provided by the XMLHttpRequest object listens for your communication status on the server side
- Receives and processes the data results that the server responds to the client
- Update the processing results to an HTML page
2.1 Creating an XMLHttpRequest object
The XMLHttpRequest() constructor is used to initialize an XMLHttpRequest instance object
const xhr = new XMLHttpRequest();
Copy the code
2.2 Establishing a Connection with the server
Establish a connection to the server through the open() method of the XMLHttpRequest object
xhr.open(method, url, [async][, user][, password])
Copy the code
Parameter Description:
- Method: indicates the current request mode, including GET and POST
- Url: indicates the server address
- Async: Boolean value indicating whether an operation is performed asynchronously. The default value is true
- User: An optional user name used for authentication. The default is null
- Password: Optional password used for authentication. The default value is NULL
2.3 Sending Data to the Server
The data from the client page is sent to the server through the send() method of the XMLHttpRequest object
xhr.send([body])
Copy the code
Body: The body of data to be sent in an XHR request, null if no data is passed.
- Add the request data to the URL address in the open() method
- Set the parameter in the send() method in the send request data to null
2.4 Bind the onReadyStatechange event
Onreadystatechange event is used to monitor the server communication state, mainly to monitor properties for XMLHttpRequest. ReadyState,
About XMLHttpRequest. The readyState attribute has five state, as the chart shows:
A readyStatechange event is emitted whenever the readyState property value changes
XMLHttpRequest. The responseText property used to receive the server response results
Here’s an example:
const request = new XMLHttpRequest()
request.onreadystatechange = function(e){
if(request.readyState === 4) {// The entire request process is complete
if(request.status >= 200 && request.status <= 300) {console.log(request.responseText) // The result returned by the server
}else if(request.status >=400) {console.log(Error message: + request.status)
}
}
}
request.open('POST'.'http://xxxx')
request.send()
Copy the code
Three, encapsulation
With the XMLHttpRequest object in mind, let’s wrap a simple Ajax request
Encapsulate an Ajax request
function ajax(options) {
// Create an XMLHttpRequest object
const xhr = new XMLHttpRequest()
// Initialize the contents of the parameters
options = options || {}
options.type = (options.type || 'GET').toUpperCase()
options.dataType = options.dataType || 'json'
const params = options.data
// Send the request
if (options.type === 'GET') {
xhr.open('GET', options.url + '? ' + params, true)
xhr.send(null)}else if (options.type === 'POST') {
xhr.open('POST', options.url, true)
xhr.send(params)
// Receive the request
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let status = xhr.status
if (status >= 200 && status < 300) {
options.success && options.success(xhr.responseText, xhr.responseXML)
} else {
options.fail && options.fail(status)
}
}
}
}
Copy the code
The usage is as follows:
ajax({
type: 'post'.dataType: 'json'.data: {},
url: 'https://xxxx'.success: function(text,xml){// The callback function after the request succeeds
console.log(text)
},
fail: function(status){//// Callback function for failed request
console.log(status)
}
})
Copy the code
Welcome to 👍, leave a message