Esempio PHP - AJAX e XML
AJAX può essere utilizzato per la comunicazione interattiva con un file XML.
Esempio XML AJAX
L'esempio seguente dimostrerà come una pagina Web può recuperare informazioni da un file XML con AJAX:
Esempio
CD info will be listed here...
Esempio spiegato - La pagina HTML
Quando un utente seleziona un CD nell'elenco a discesa sopra, viene eseguita una funzione chiamata "showCD()". La funzione viene attivata dall'evento "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>
La funzione showCD() esegue le seguenti operazioni:
- Controllare se è selezionato un CD
- Creare un oggetto XMLHttpRequest
- Creare la funzione da eseguire quando la risposta del server è pronta
- Invia la richiesta a un file sul server
- Si noti che un parametro (q) viene aggiunto all'URL (con il contenuto dell'elenco a discesa)
Il file PHP
La pagina sul server chiamata dal JavaScript sopra è un file PHP chiamato "getcd.php".
Lo script PHP carica un documento XML, " cd_catalog.xml ", esegue una query sul file XML e restituisce il risultato come 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>");
}
}
?>
Quando la query del CD viene inviata da JavaScript alla pagina PHP, accade quanto segue:
- PHP crea un oggetto DOM XML
- Trova tutti gli elementi <artista> che corrispondono al nome inviato da JavaScript
- Emetti le informazioni sull'album (invia al segnaposto "txtHint")