<html>
<head>
<title> Ajax实例</title>
<script language = "javascript" type ="text/javascript">
//定义一个变量,存放xmlhttprequest对象
var xmlHttp;
//定义一个用于创建xmlhttprequest对象的函数
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
//响应HTTP请求状态变化的函数
function httpStateChange() {
//判断异步调用是否完成
if (xmlHttp.readyState == 4) {
//判断异步调用是否成功,如果成功则开始局部更新数据
if (xmlHttp.status == 200 || xmlHttp.status == 0) {
//查找节点
var node = document.getElementById("myDiv");
//更新数据
node.firstChild.nodeValue = xmlHttp.responseText;
}
else {
//如果异步未成功
alert("异步调用出错\n返回的HTTP状态为:" + xmlHttp.status + "\n返回的Http状态信息为:" + xmlHttp.statusText);
}
}
}
//异步调用服务器端数据
function getData() {
//创建xmlhttprequest对象
createXMLHttpRequest();
if (xmlHttp != null) {
//创建http请求
xmlHttp.open("get", "ajax.txt", true);
//设置响应htttp请求状态变化的函数
xmlHttp.onreadystatechange = httpStateChange;
//发生请求
xmlHttp.send(null);
}
}
</script>
</head>
<body>
<div id = "myDiv" >原数据</div>
<input type ="button" value ="更新数据" onclick = "getData()"/>
</body>
</html>