AJAX dapat digunakan untuk komunikasi interaktif dengan file XML.
Contoh berikut akan menunjukkan bagaimana halaman web dapat mengambil informasi dari file XML dengan AJAX:
Contoh:
Ketika pengguna memilih CD dalam daftar dropdown di atas, fungsi yang disebut “showCD()
” dijalankan. Fungsi ini dipicu oleh peristiwa “onchange
“:
<html> <head> <script> function showCD(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (this.readyState==4 && this.status==200) { document.getElementById("txtHint").innerHTML=this.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="Bee Gees">Bee Gees</option> <option value="Cat Stevens">Cat Stevens</option> </select> </form> <div id="txtHint"><b>CD info will be listed here...</b></div> </body> </html>
Fungsi showCD() melakukan hal berikut:
Halaman di server yang disebut dengan JavaScript di atas adalah file PHP yang disebut “getcd.php”.
Skrip PHP memuat dokumen XML, “cd_catalog.xml”, menjalankan kueri terhadap file XML dan mengembalikan hasilnya sebagai 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++) { //Process only element nodes 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++) { //Process only element nodes if ($cd->item($i)->nodeType==1) { echo("<b>" . $cd->item($i)->nodeName . ":</b> "); echo($cd->item($i)->childNodes->item(0)->nodeValue); echo("<br>"); } } ?>
Ketika kueri CD dikirim dari JavaScript ke halaman PHP, hal berikut akan terjadi: