PHP 新手入門之AJAX與XML

接下來我們以案例來詳解:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<script>
function showUser(str){
	if (str==""){
		document.getElementById("txtHint").innerHTML="";
		return;
	} 
	if (window.XMLHttpRequest){
		// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
		xmlhttp=new XMLHttpRequest();
	}else{
		// IE6, IE5 浏览器执行代码
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
		}
	}
	xmlhttp.open("GET","3_2.php?q="+str,true);
	xmlhttp.send();
}
</script>
</head>
<body>

<form>
	<select name="users" onchange="showUser(this.value)">
		<option value="">Select a person:</option>
		<option value="1">Peter Griffin</option>
		<option value="2">Lois Griffin</option>
		<option value="3">Glenn Quagmire</option>
		<option value="4">Joseph Swanson</option>
	</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>

接下來我們建立一個php 的文件,程式碼如下:

<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++)
{
	// 处理元素节点
	if ($x->item($i)->nodeType==1)
	{
		if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
		{
			$y=($x->item($i)->parentNode);
		}
	}
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++)
{ 
	// 处理元素节点
	if ($cd->item($i)->nodeType==1)
	{
		echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
		echo($cd->item($i)->childNodes->item(0)->nodeValue);
		echo("<br>");
	}
}
?>

當CD 查詢從JavaScript 發送到PHP 頁面時,將會發生:

1. PHP 建立XML DOM 物件

2. 找出所有<artist> 元素中與JavaScript 所傳資料相符的名字

3. 輸出album 的訊息,並發回"txtHint" 佔位符

註:本段程式碼要大家複製到本地測試,前提是要有上一節我們所說的資料庫表

繼續學習
||
<!DOCTYPE html> <html> <meta charset="utf-8"> <head> <script> function showUser(str){ if (str==""){ document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码 xmlhttp=new XMLHttpRequest(); }else{ // IE6, IE5 浏览器执行代码 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","3_2.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <br> <div id="txtHint"><b>Person info will be listed here.</b></div> </body> </html>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!