Onreadystatechange event
When a request is sent to the server, we need to execute some response-based tasks.
When the readystate changes, the onreadystatechange event is triggered.
The readystate attribute contains the status information of XMLHttpRequest.
The following are three important attributes of the XMLHTTPRequest object:
Attribute
Description
Onreadystatechange
A storage function (or function name) that is called whenever the readystate attribute changes.
Readystate
XMLHttpRequest status. Changes from 0 to 4.
- 0: the request is not initialized.
- 1: The server connection has been established.
- 2: The request has been received
- 3: The request is being processed
- 4: The request is complete and the response is ready.
Status
200: "OK"
404: Page not found
In the onreadystatechange event, we specify the tasks executed when the server responds to the prepared tasks.
When readystate is 4 and the status is 200, the response is ready:
XMLHTTP. onreadystatechange = function () {If (XMLHTTP. readystate = 4 & XMLHTTP. status = 200) {document. getelementbyid ("mydiv "). innerhtml = XMLHTTP. responsetext ;}}
Note: The onreadystatechange event is triggered four times, corresponding to each change in readystate.
Use the callback function
The callback function is a function that is passed to another function as a parameter.
If your website has multiple Ajax tasks, you should writeStandardAnd call this function for each Ajax task.
This function call should contain URLs and tasks executed when the onreadystatechange event occurs (each call may be different ):
Function myfunction () {loadxmldoc ("ajax_info.txt", function () {If (XMLHTTP. readystate = 4 & XMLHTTP. status = 200) {document. getelementbyid ("mydiv "). innerhtml = XMLHTTP. responsetext ;}});}