XMLHttpRequest 对象
XMLHttpRequest 对象提供了在网页加载后与服务器进行通信的方法。
什么是 XMLHttpRequest 对象?
XMLHttpRequest 对象是开发者的梦想,因为您能够:
- 在不重新加载页面的情况下更新网页
- 在页面已加载后从服务器请求数据
- 在页面已加载后从服务器接收数据
- 在后台向服务器发送数据
所有现代的浏览器都支持 XMLHttpRequest 对象。
创建 XMLHttpRequest 对象
通过一行简单的 JavaScript 代码,我们就可以创建 XMLHttpRequest 对象。
在所有现代浏览器中(包括 IE 7):
xmlhttp=new XMLHttpRequest()
在 Internet Explorer 5 和 6 中:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
实例
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
// ...our code here...
}
else
{
alert("Problem retrieving XML data");
}
}
}
</script>
注释:onreadystatechange 是一个事件句柄。它的值 (state_Change) 是一个函数的名称,当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。仅在状态为 4 时,我们才执行代码。
本文介绍了XMLHttpRequest对象的基本概念及其使用方法,展示了如何通过简单的JavaScript代码创建该对象,并详细解释了其在网页与服务器间通信的应用场景。
904

被折叠的 条评论
为什么被折叠?



