Gli ultimi tutorial di sviluppo web
 

PHP Esempio - AJAX e XML


AJAX può essere utilizzato per la comunicazione interattiva con un file XML.


AJAX XML Esempio

Il seguente esempio dimostrerà come una pagina web può recuperare le 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, una funzione chiamata " showCD() " viene eseguita. La funzione viene attivata dal "onchange" evento:

<html>
<head>
<script>
function showCD(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for 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="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>

Lo showCD() la funzione esegue le seguenti operazioni:

  • Verificare se è stato selezionato un CD
  • Creare un oggetto XMLHttpRequest
  • Creare la funzione da eseguire quando la risposta del server è pronto
  • Invia la richiesta fuori ad 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 chiamato dal JavaScript di cui sopra è un file PHP chiamato "getcd.php" .

Lo script PHP carica un documento XML, " cd_catalog.xml ", esegue una query contro il 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 CD viene inviato dal JavaScript alla pagina PHP, accade quanto segue:

  1. PHP crea un oggetto DOM XML
  2. Trova tutti i <artist> elementi che corrisponde al nome inviato dal JavaScript
  3. Uscita le informazioni sull'album (send to the "txtHint" placeholder)