- 论坛徽章:
- 0
|
[ 本帖最后由 tkchks 于 2011-12-25 19:13 编辑 ]
使用XMLHttpRequest对象发送请求的基本步骤如下:
创建一个XMLHttpRequest的引用
告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要设置onreadystatechange属性
指定请求的属性。open()
将请求发送给服务器。send()
xmlHttp.responseText将响应提供为一个串
以下示例代码包括两个文件,分别为:
simpleRequest.html和simpleResponse.xml
以下为其完整代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>simpleRequest.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<script type="text/javascript" >
var xmlHttp;
//创建一个XMLHttpRequest对象
function createXMLHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
//开始一个请求
function startRequest()
{
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET","simpleResponse.xml",true);
xmlHttp.send(null);
}
//当xmlHttp对象的内部状态发生变化时候,调用此处理函数
//一旦接受到相应(readyState为4)
function handleStateChange()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
alert("The server replied with:"+xmlHttp.responseText);
document.getElementById("result").innerHTML = xmlHttp.responseText;
}
}
}
</script>
<body>
<form>
<input type="button" value="Start Basic Asynchronous Request" onclick="startRequest();" />
</form>
<div id="result" style="boder:1px solid red;width:400px;height:200px;">box</div>
<hr/>
<ul>使用XMLHttpRequest对象发送请求的基本步骤如下:
<li>创建一个XMLHttpRequest的引用</li>
<li>告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要设置onreadystatechange属性</li>
<li>指定请求的属性。open()</li>
<li>将请求发送给服务器。send()</li>
<li>xmlHttp.responseText将响应提供为一个串</li>
</ul>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<author>Henry</author>
<pubdate>2011-11-11</pubdate>
<Subject>西游记</Subject>
</book>
<book>
<author>Kater</author>
<pubdate>2015-11-11</pubdate>
<Subject>娃哈哈</Subject>
</book>
</books>
效果:当点击页面上的button后,会alert出一个框,其中内容为xml文件中的内容。然后在html页面中id=result的div中显示xml中的信息。 |
|