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>
提交重置代码
章节
笔记
提问
课件
反馈
捐赠

PHP 新手入门教程