Home >Web Front-end >JS Tutorial >Explanation of ajax request process and request method (code example)

Explanation of ajax request process and request method (code example)

不言
不言forward
2018-11-14 09:59:113649browse

This article brings you an explanation (code example) about the ajax request process and request method. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The full name of ajax is Asynchronous JavaScript and XML. Among them, Asynchronous means asynchronous, which is different from the synchronous method used in traditional web development. According to the editor's knowledge over the wall, ajax has been around for a long time, but it was not used at that time. Later, Google used it on Google Maps. People found it very convenient to use, and the page did not need to be refreshed, and the user experience was very good ( The website at that time had no user experience^_^)

ajax principle

XMLHttpRequest is the core mechanism of ajax. It was first introduced in IE5 and is A technology that supports asynchronous requests. To put it simply, javascript can make requests to the server and process responses in a timely manner without blocking the user, achieving the effect of no page refresh

var xhr = new XMLHttpRequest()
//IE浏览器使用var xhr = new ActiveXObject
xhr.open('get', url, true)
xhr.send(null)
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            success(xhr.responseText)
        } else {
            fail && fail(xhr.status)
        }
    }
}

xhr.open()

The third parameter: true/fasle The default value is true
false means to wait for the data to be returned before continuing. If the data is not obtained, it will be stuck there until the data is obtained.
True means not waiting and returning directly. This is the so-called asynchronous data acquisition!

xhr.send

The data to be transmitted accepts a string type

xhr.onreadystatechange

The event handler that will be triggered every time the state changes

xhr.readyState has the following states

0 The request is not initialized and the open method has not been called

1 The server connection has been established, the open method has been called, and the send method has not been called yet

2 The request has been received, that is, the header information has been received

3 The request is being processed, that is, received The response body is reached. At this time, because the response and http header are incomplete, an error will occur when obtaining part of the data through responseBody and responseText.

4 The request has been completed and the data has been received. At this time, it can be obtained through responseXml and responseText. Complete response data

xhr.statusCommon HTTP status

0**: Not initialized

1**: Request received, Continue processing

2**: The operation was successfully received, analyzed, and accepted

3**: This request must be processed further

4**: The request contains an error Syntax or cannot be completed

5**: The server failed to perform a fully valid request

jQuery.ajax

$.ajax({
    url: '',
    Type: '',
    data: '',
    async:true,
    dataType: '',
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Access-Toke");
    },
    success: function (data) {
        fn1()
    },
    error: function (err) {
       error && error(err) 
    }
})
fn2()

success-function

$.ajax Whether the success method obtains a successful callback, jQuery determines the following states. There is the following code in the source code (approximately line 8193)

isSuccess = status >= 200 && status < 300 || status === 304

304- --The usual saying is that the browser still has a cache, and the server tells the client that the original cached document can continue to be used

async-Boolean value

async default setting The value is true, which is an asynchronous method. That is to say, after ajax sends a request, while waiting for the server to return, the front desk will continue to execute the script behind the ajax block until the server returns the correct result. success, that is to say, two threads are executed at this time, one thread after the ajax block sends the request and the script after the ajax block (another thread)

When asyn is set to false, then the ajax request Synchronous, that is to say, after the ajax block sends a request at this time, it will wait at fn1() and will not execute fn2() until the fn1() part is executed.

dataType--String

dataType can specify the following values

xml: Returns an XML document, which can be processed with JQuery

html : Returns plain text HTML information; the included script tag will be executed when inserted into the DOM

script: Returns plain text JavaScript code. Results are not automatically cached. Unless cache parameters are set. Note that during remote requests (not under the same domain), all post requests will be converted into get requests

json: Return JSON data

jsonp: JSONP format. When calling a function using the SONP form, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function

text: Return a plain text string

beforeSend--Function

Function that can modify the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If false is returned in beforeSend, this ajax request can be canceled. The XMLHttpRequest object is the only parameter

ajax advantages and disadvantages

Advantages: Improve user experience through asynchronous, reduce unnecessary data round-trips, and achieve partial refresh

Disadvantages: Yes Search engine support is relatively weak

The above is the detailed content of Explanation of ajax request process and request method (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete