PHP AJAX and XML instance
AJAX can be used to communicate interactively with the XML file.
AJAX XML instance
The following examples will demonstrate how a web page via AJAX reading information from an XML file:
Examples
CD info will be listed here...
Examples explain - HTML page
When a user in the above drop-down list to select a Double CD, it performs named "showCD ()" function. This function by the "onchange" event is triggered:
<html> <head> <script> function showCD(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","getcd.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> Select a CD: <select name="cds" onchange="showCD(this.value)"> <option value="">Select a CD:</option> <option value="Bob Dylan">Bob Dylan</option> <option value="Bonnie Tyler">Bonnie Tyler</option> <option value="Dolly Parton">Dolly Parton</option> </select> </form> <div id="txtHint"><b>CD info will be listed here...</b></div> </body> </html>
showCD () function performs the following steps:
- Check whether the CD is selected
- Create XMLHttpRequest object
- Create function when the server is ready to perform the response
- File on the server to send requests
- Please note added to the end of the URL parameter (q) (contains the contents of the drop-down list)
PHP File
The above servers through JavaScript calling this page is called "getcd.php" PHP file.
PHP script to load an XML document, " cd_catalog.xml ", to run queries against XML file and returns the result as HTML:
<?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>"); } } ?>
When the CD query is sent from JavaScript to PHP page will occur:
- PHP create XML DOM object
- Find all <artist> element with JavaScript preached data matching names
- Output album information, and sends back "txtHint" placeholder