#on
This When the request is sent to the server, we need to perform some response -based tasks.
Whenever readyState changes, the onreadystatechange event will be triggered.
ReadyState attributes have status information of XMLHTTPREQUEST.
Below is the three important attributes of the XMLHTTPREQUEST object:
In the onreadystatechange event, we specify the tasks to be performed when the server response is ready to be processed.
When readyState is equal to 4 and the status is 200, it means that the response is ready
Note: The onreadystatechange event is triggered 5 times (0 - 4), corresponding to each change in readyState.
2. Use the Callback function The callback function is a function that is passed to another function in the form of parameters.
If there are multiple AJAX tasks on your website, you should write a standard function for creating the XMLHTTPRequest object and call the function for each AJAX task.
This function call should include the URL and the task to be performed when the onreadystatechange event occurs (each call may be different):
The following demonstrates a page with two AJAX tasks:
Code 5_1.php<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var xmlhttp;
//标准函数
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction1()
{
loadXMLDoc("5_2.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv1").innerHTML=xmlhttp.responseText;
}
});
}
function myFunction2()
{
loadXMLDoc("5_3.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv2").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<!-- 按下按钮,调用myFunction1() -->
<div id="myDiv1"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction1()">NO:1 通过 AJAX 改变内容</button>
<hr/>
<!-- 按下按钮,调用myFunction2() -->
<div id="myDiv2"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction2()">NO:2通过 AJAX 改变内容</button>
</body>
</html>
AJAX is not a programming language.
It is just a technique for creating better and more interactive web applications.
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。