您的位置:首页 > 理论基础 > 计算机网络

Ajax - XMLHttpRequest对象的属性responseText

2007-08-07 14:50 429 查看
XMLHttpRequest对象提供了两个可以用来访问服务器响应的属性。第一个属性respo-
nseText将响应提供为一个串,第二个属性responseXML将响应提供为一个XML对象。

简单来说就是responseText返回的是xml文件的全部内容的字符串。如果内容为123,那responseText返回的是"123"的字符串;内容是<head>123</head>,那responseText返回的是“<head>123</head>”的字符串 。

像innerHTML.xml

<table border="1">

<tbody>

<tr>

<th>Activity Name</th>

<th>Location</th>

<th>Time</th>

</tr>

<tr>

<td>Waterskiing</td>

<td>Dock #1</td>

<td>9:00 AM</td>

</tr>

<tr>

<td>Volleyball</td>

<td>East Court</td>

<td>2:00 PM</td>

</tr>

<tr>

<td>Hiking</td>

<td>Trail 3</td>

<td>3:30 PM</td>

</tr>

</tbody>

</table>

这个内容放在HTML页面是就是完全的一个表的格式。

结合使用HTML元素的innerHTML属性,responseText属性就会变得非常有用。

下面是一个点击search按钮而且在窗口内容中增加了结果表的例子

1.点击search按钮,调用startRequest函数,它先调用createXMLHttpRequest函数来初始化XMLHttpRequest对象的一个新实例;

2. startRequest函数将回调函数设置为handleStateChange函数;

3. startRequest函数使用open()方法来设置请求方法(GET)及请求目标,并且设置为异步地完成请求;

4. 使用XMLHttpRequest对象的send()方法发送请求;

5. XMLHttpRequest对象的内部状态每次有变化时,都会调用handleStateChange函数。一旦接收到响应(如果readyState属性的值为4),div元素的innerHTML属性就将使用XMLHttpRequest对象的responseText属性设置。

代码清单3-1 innerHTML.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Using responseText with innerHTML</title>

<script type="text/javascript">

var xmlHttp;

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", "innerHTML.xml", true);

xmlHttp.send(null);

}

function handleStateChange() {

///请求的状态,有5个值:0=未初始化,1=正在加载,2=已加载,3=交互中,4=完成

if(xmlHttp.readyState == 4) {

if(xmlHttp.status == 200) {

document.getElementById("results").innerHTML = xmlHttp.responseText;

}

}

}

</script>

</head>

<body>

<form action="#">

<input type="button" value="Search for Today's Activities"

onclick="startRequest();"/>

</form>

<div id="results"></div>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: