English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In questa sezione, mostriamo come inviare una richiesta AJAX a un file PHP e come recuperare il contenuto del file PHP.
L'esempio seguente mostra come la pagina web comunica con il server e recupera il contenuto del file PHP:
Nell'esempio sopra, l'evento fetchDoc() esegue una funzione onclick.
Questo è il codice HTML:
<button type="button" onclick="fetchDoc()">Fetch Content</button> <div id="output"></div> <script> funzione fetchDoc() { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { document.getElementById("output").innerHTML = this.responseText; } }; httpRequest.open("GET", "ajax_time.php", true); httpRequest.send(); } </script>
Questo è il codice PHP (ajax_time.php):
<?php echo date("d/m/Y, h:i:s A"); ?>
L'esempio seguente mostra come la pagina web comunica con il server web quando l'utente scrive un carattere nel campo di input:
Inizia a scrivere il nome della nazione/regione nel campo di input seguente:
Nazione:
Suggerimenti e commenti:
Nell'esempio sopra, quando l'utente scrive un carattere nel campo di input, l'evento showHint() esegue la funzione onkeyup.
Questo è il codice HTML:
<!DOCTYPE html> <html> <div> <p>Inizia a scrivere il nome della nazione/regione nel campo di input seguente:</p> <p>Nazione: <input type="text" onkeyup="showHint(this.value)"></p> <p>Consigli: <span id="result"></span></p> </div> <script> var elem = document.getElementById("result"); funzione showHint(name) { se (name.length === 0) { elem.innerHTML = ""; return; } else { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { elem.innerHTML = this.responseText; } }; httpRequest.open("GET", "ajax_hint.php?q=" + name, true); httpRequest.send(); } } </script> </html>
Questo è il codice PHP (ajax_hint.php):
<?php //Array dei nomi di stato $countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",...); //Ottiene il parametro q dall'URL $q = $_REQUEST["q"]; $hint = ""; //Se $q è diverso dai suggerimenti nell'array, si itera attraverso tutti i suggerimenti nell'array "" if ($q !== "") { $q = strtolower($q); $len = strlen($q); foreach($countries as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "") { $hint = $name; } else { $hint .= ", $name"; } } } } //Se non vengono trovati suggerimenti o viene outputto il valore corretto, viene outputto "no suggestion" echo $hint === "" ? "no suggestion" : $hint; ?>
Per una lista completa dei nomi di stato, vederehttps://gist.github.com/DHS/1340150