AJAX的服务器响应内容
ajax的服务器响应内容:
使用XMLHttpRequest对象的responseText或者responseXML属性可以获取来自服务器的响应内容。
两个属性功能列表如下:
| 属性 | 描述 |
| responseText | 获得字符串形式的响应数据。 |
| responseXML | 获得XML形式的响应数据。 |
一.responseText属性:
如果来自服务器响应内容不是XML,那么要使用responseText属性来获取。此属性返回值是字符串格式的,使用方式演示如下:
document.getElementById("show").innerHTML=xmlhttp.responseText;完整代码实例:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.php.cn/" />
<title>php中文网</title>
<script>
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("show").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","demo/ajax/txt/demo.txt",true);
xmlhttp.send();
}
window.onload=function(){
var obt=document.getElementById("bt");
obt.onclick=function(){
loadXMLDoc();
}
}
</script>
</head>
<body>
<div id="show"><h2>原来的内容</h2></div>
<button type="button" id="bt">查看效果</button>
</body>
</html>点击按钮可以获取文本文件中的内容,并通过responseText属性写入到div中。
二.responseXML属性:
如果来自服务器的响应是XML,并且需要作为XML对象进行解析,那么就需要使用responseXML属性,使用方式演示如下:
var xmlDoc = xmlhttp.responseXML;
responseXML属性的返回值是一个XML对象,完整对象实例如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="author" content="http://www.php.cn/" />
<title>php中文网</title>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var xmlDoc = xmlhttp.responseXML;
var str = "";
var targets = xmlDoc.getElementsByTagName("target");
for (index = 0; index < targets.length; index++) {
str = str + targets[index].childNodes[0].nodeValue + "<br>";
}
document.getElementById("show").innerHTML = str;
}
}
xmlhttp.open("GET", "demo/ajax/xml/XML.xml", true);
xmlhttp.send();
}
window.onload = function () {
var obt = document.getElementById("bt");
obt.onclick = function () {
loadXMLDoc();
}
}
</script>
</head>
<body>
<div>
<div id="show"></div>
<input id="bt" type="button" value="查看效果"/>
</div>
</body>
</html>

hopol
请问,target1.chilldren1/target2.chilldren2/target3.chilldren3/。。。。xml节点是一对一的关系么。
7年前 添加回复 0