AJAX - onreadystatechange event
onreadystatechange event
When a request is sent to the server, based on the response we need to perform some tasks.
Whenever readyState changes will trigger onreadystatechange event.
there XMLHttpRequest readyState property status information.
Here is the XMLHttpRequest object three important properties:
属性 | 描述 |
---|---|
onreadystatechange | 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 |
readyState | 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
|
status | 200: "OK" 404: 未找到页面 |
In the onreadystatechange event, we require that the server responds when the task is ready to be processed when executed.
When the readyState and status equal to 4 to 200, a response ready:
Examples
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
Note: onreadystatechange event is triggered 5 times (0--4), corresponding to each of the readyState changes.
Using callback functions
Is a callback function passed as a parameter to another function.
If multiple AJAX tasks exist on your site, then you should create XMLHttpRequest object to write a standard function, and the function is called for each AJAX task.
URL should contain the function call and the tasks performed onreadystatechange event occurs (for each call may vary):
Examples
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}