PHP - AJAX and XML

AJAX can be used to communicate interactively with XML files.


AJAX XML Example

The following example will demonstrate how a web page reads information from an XML file through AJAX:

27.png

When the user selects a CD in the drop-down list above, a function named "showCD()" will be executed. This function is triggered by the "onchange" event:

    PHP中文网  
Select a CD:
CD info will be listed here...

showCD() function will perform the following steps:

· Check whether a CD is selected

· Create an XMLHttpRequest object

· Create a function that executes when the server response is ready

· Send a request to a file on the server

Please note the parameter (q) added to the end of the URL (containing the drop-down list Content


xml file

  Empire Burlesque Bob Dylan USA Columbia 10.90 1985   Maggie May Rod Stewart UK Pickwick 8.50 1990   Black angel Savage Rose EU Mega 10.90 1995   The dock of the bay Otis Redding USA Atlantic 7.90 1987  



PHP file

The server page called above through JavaScript is a PHP file named "getcd.php"

The PHP script loads the XML document, "cd_catalog.xml", runs the query against the XML file, and returns the results in HTML:

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("" . $cd->item($i)->nodeName . ": "); echo($cd->item($i)->childNodes->item(0)->nodeValue); echo("
"); } } ?>

When When a CD query is sent from JavaScript to a PHP page, what happens is:

1. PHP creates an XML DOM object

2. Finds all elements that match the data passed by JavaScript Name

3. Output the album information and send back "txtHint" placeholder

Program result display:

59.png


Continuing Learning
||
Empire Burlesque Bob Dylan USA Columbia 10.90 1985 Sylvias Mother Dr.Hook UK CBS 8.10 1973 Maggie May Rod Stewart UK Pickwick 8.50 1990 Black angel Savage Rose EU Mega 10.90 1995 The dock of the bay Otis Redding USA Atlantic 7.90 1987
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!