PHP开发基础教程之服务器响应
一、如何获得服务器响应
想要获得服务器的响应,可以使用XMLHttpRequest 对象的 responseText 或 responseXML 属性。

二、responseText属性
如果来自服务器的响应并非 XML,请使用 responseText 属性。
responseText 属性返回字符串形式的响应,因此您可以这样使用:
利用4_1.php 从4_2.txt中读取信息
4_1.php 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","4_2.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">通过AJAX改变内容</button>
<div id="myDiv">AJAX</div>
</body>
</html>4_2.txt代码
* AJAX 是一种用于创建快速动态网页的技术。
三、responseXML属性
如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性:
请求 4_4.xml 文件,并解析响应(通俗的说就是在4_3.php页面不刷新读取4_4.xml里面的响应内容):
4_3.php代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
var txt,x,i;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    xmlDoc=xmlhttp.responseXML;
    txt="";
    x=xmlDoc.getElementsByTagName("title");
    for(i=0;i<x.length;i++){
    		txt=txt+x[i].childNodes[0].nodeValue+"<br/>";
    	}
    document.getElementById("myDiv").innerHTML=txt
    }
  }
xmlhttp.open("GET","4_4.xml",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">通过AJAX改变内容</button>
<div id="myDiv">AJAX</div>
</body>
</html>4_4.xml代码
<!-- Copyright php.cn --> <bookstore> <book category="children"> <title>Harry Potter</title ><author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="cooking"> <title>Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="web" cover="paperback"> <title>Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book><book category="web"> <title>XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> </bookstore>
			
									
									
									
									
									
									
									
									
									
									
									
									
  
            
        
素颜
东西好多,直接不想看了,也看不明白!
8年前 添加回复 0