您的位置:首页 > 其它

Ajax异步请求实例

2015-03-06 10:04 225 查看
Ajax中的onreadystatechange 是一个事件句柄。 它的值 (state_Change) 是一个函数的名称, 当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。

xmlhttpeDemo.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META   HTTP-EQUIV="nocache"   CONTENT="no-cache"/>
<title></title>

<!--   onreadystatechange 是一个事件句柄。
它的值 (state_Change) 是一个函数的名称,
当 XMLHttpRequest 对象的状态发生改变时,
会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。
仅在状态为 4 时,我们才执行代码-->

<script type="text/javascript">
var xmlhttp = null;
function  loadXMLDoc(url) {
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
if (window.ActiveXObject)
xmlhttp = new ActiveXObject("Microsoft.XMLHttp");
if (xmlhttp != null) {
xmlhttp.onreadystatechange = state_Change;
xmlhttp.open("GET", url, true); //true - 异步处理
xmlhttp.send(null);
}
}

function  state_Change() {
if (xmlhttp.readyState == 4) {
alert("Ready,State: " + xmlhttp.readyState);
if (xmlhttp.status == 200) {
document.getElementById('A1').innerHTML = xmlhttp.status;
document.getElementById('A2').innerHTML = xmlhttp.statusText;
document.getElementById('A3').innerHTML = xmlhttp.responseText;
}
} else {
alert("No ready,State: " + xmlhttp.readyState);
}
}
</script>
</head>
<body>
<p><b>Status:</b>
<span id="A1"></span>
</p>

<p><b>Status text:</b>
<span id="A2"></span>
</p>

<p><b>Response:</b>
<br /><span id="A3"></span>
</p>

<button onclick="loadXMLDoc('xmlText.xml')">Get XML</button>
</body>
</html>


xmlText.xml

<?xml version="1.0" encoding="utf-8" ?>
<message>
<from>John</from>
<to>Amy</to>
<msg>Come here tonight!</msg>
</message>


只有一当readyState=4的时候,才能读取xmlText.xml的内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: