After a request is sent, the client cannot determine when the request will be completed. Therefore, an event mechanism is required to capture the request State. The XMLHttpRequest object provides the onreadyStateChange event to implement this function. This is similar to the callback function. The onreadyStateChange event specifies an event processing function to process the execution results of the XMLHttpRequest object, for example:
Copy codeThe Code is as follows:
AjaxObj = createAjaxObject ();
Var url = "/MyTodoes/FetchText? Id = "+ id;
AjaxObj. open ("Get", url, true );
AjaxObj. onreadyStateChange = changeTabCallBack;
AjaxObj. send (null );
After reading the W3C explanation, let's look at this example to better understand it.
The onreadyStateChange event is triggered when the readyState attribute changes. The value of readyState indicates the status of the current request. You can perform different processing based on this value in the event processing program. ReadyState can be set to 0: not initialized, 1: Loading, 2: Loading, 3: processing, and 4: processing. Once the value of the readyState attribute is changed to 4, you can access the response data returned by the server.
The value of readyState in an event is usually processed only after the request is completed, for example:
Copy codeThe Code is as follows:
Function changeTabCallBack (){
If (ajaxObj. readyState = 4 ){
// Perform the next Verification
}
}
Status stores the Http request response code returned by the server, which indicates the request processing result. The meaning of common response codes is as follows: Right.
In Ajax development, the most common response code is 200. The Code is as follows:
Copy codeThe Code is as follows:
Function changeTabCallBack (){
If (ajaxObj. readyState = 4 ){
If (ajaxObj. status = 200 ){
// The server returns the correct data and starts Response Processing.
}
}
}
Http Status Code Description
200 successful request
202 requests accepted but not processed
400 Error request
404 The requested resource is not found
500 Internal Server Error