PHP開發(fā)基礎(chǔ)教程之服務(wù)器響應(yīng)
一、如何獲得服務(wù)器響應(yīng)
想要獲得服務(wù)器的響應(yīng),可以使用XMLHttpRequest 對象的 responseText 或 responseXML 屬性。
二、responseText屬性
如果來自服務(wù)器的響應(yīng)并非 XML,請使用 responseText 屬性。
responseText 屬性返回字符串形式的響應(yīng),因此您可以這樣使用:
利用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改變內(nèi)容</button> <div id="myDiv">AJAX</div> </body> </html>
4_2.txt代碼
* AJAX 是一種用于創(chuàng)建快速動(dòng)態(tài)網(wǎng)頁的技術(shù)。
三、responseXML屬性
如果來自服務(wù)器的響應(yīng)是 XML,而且需要作為 XML 對象進(jìn)行解析,請使用 responseXML 屬性:
請求 4_4.xml?文件,并解析響應(yīng)(通俗的說就是在4_3.php頁面不刷新讀取4_4.xml里面的響應(yīng)內(nèi)容):
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改變內(nèi)容</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>