L' oggetto XMLHttpRequest
Tutti i browser moderni hanno un oggetto XMLHttpRequest integrato per richiedere dati da un server.
Tutti i principali browser hanno un parser XML integrato per accedere e manipolare XML.
L'oggetto XMLHttpRequest
L'oggetto XMLHttpRequest può essere utilizzato per richiedere dati da un server web.
L'oggetto XMLHttpRequest è il sogno di uno sviluppatore , perché puoi:
- Aggiorna una pagina web senza ricaricare la pagina
- Richiedi dati da un server - dopo che la pagina è stata caricata
- Ricevi dati da un server - dopo che la pagina è stata caricata
- Invia dati a un server - in background
Esempio di richiesta XMLHttp
Quando si digita un carattere nel campo di input sottostante, viene inviata una XMLHttpRequest al server e vengono restituiti alcuni suggerimenti sui nomi (dal server):
Esempio
Start typing a name in the input field below:
Suggestions:
Invio di una richiesta XMLHttp
Tutti i browser moderni hanno un oggetto XMLHttpRequest integrato.
Una sintassi JavaScript comune per l'utilizzo è molto simile a questa:
Esempio
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Action to be performed when the
document is read;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
Creazione di un oggetto XMLHttpRequest
La prima riga nell'esempio sopra crea un oggetto XMLHttpRequest:
var xhttp = new XMLHttpRequest();
L'evento onreadystatechange
La proprietà readyState mantiene lo stato di XMLHttpRequest.
L' evento onreadystatechange viene attivato ogni volta che readyState cambia.
Durante una richiesta del server, readyState cambia da 0 a 4:
0: richiesta non inizializzata
1: connessione al server stabilita
2: richiesta ricevuta
3: richiesta in elaborazione
4: richiesta terminata e risposta pronta
Nella proprietà onreadystatechange, specificare una funzione da eseguire quando readyState cambia:
xhttp.onreadystatechange = function()
Quando readyState è 4 e status è 200, la risposta è pronta:
if (this.readyState == 4 && this.status == 200)
Proprietà e metodi di XMLHttpRequest
Method | Description |
---|---|
new XMLHttpRequest() | Creates a new XMLHttpRequest object |
open(method, url, async) | Specifies the type of request method: the type of request: GET or POST url: the file location async: true (asynchronous) or false (synchronous) |
send() | Sends a request to the server (used for GET) |
send(string) | Sends a request string to the server (used for POST) |
onreadystatechange | A function to be called when the readyState property changes |
readyState | The status of the XMLHttpRequest 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
status | 200: OK 404: Page not found |
responseText | The response data as a string |
responseXML | The response data as XML data |
Accesso attraverso domini
Per motivi di sicurezza, i browser moderni non consentono l'accesso tra domini.
Ciò significa che sia la pagina web che il file XML che tenta di caricare devono trovarsi sullo stesso server.
Gli esempi su W3Schools aprono tutti i file XML che si trovano nel dominio W3Schools.
Se vuoi usare l'esempio sopra su una delle tue pagine web, i file XML che carichi devono trovarsi sul tuo server.
La proprietà responseText
La proprietà responseText restituisce la risposta come stringa.
Se si desidera utilizzare la risposta come stringa di testo, utilizzare la proprietà responseText:
Esempio
document.getElementById("demo").innerHTML = xmlhttp.responseText;
La proprietà responseXML
La proprietà responseXML restituisce la risposta come oggetto DOM XML.
Se desideri utilizzare la risposta come oggetto DOM XML, utilizza la proprietà responseXML:
Esempio
Richiedi il file cd_catalog.xml e utilizza la risposta come oggetto DOM XML:
xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
RICEVERE o POSTARE?
GET è più semplice e veloce di POST e può essere utilizzato nella maggior parte dei casi.
Tuttavia, utilizzare sempre le richieste POST quando:
- Un file memorizzato nella cache non è un'opzione (aggiorna un file o un database sul server)
- Invio di una grande quantità di dati al server (il POST non ha limiti di dimensioni)
- Inviando l'input dell'utente (che può contenere caratteri sconosciuti), POST è più robusto e sicuro di GET
L'URL - Un file su un server
Il parametro url del metodo open() è un indirizzo di un file su un server:
xmlhttp.open("GET", "xmlhttp_info.txt", true);
Il file può essere qualsiasi tipo di file, come .txt e .xml, o file di scripting del server come .asp e .php (che possono eseguire azioni sul server prima di inviare la risposta).
Asincrono: vero o falso?
Per inviare la richiesta in modo asincrono, il parametro async del metodo open() deve essere impostato su true:
xmlhttp.open("GET", "xmlhttp_info.txt", true);
L'invio di richieste in modo asincrono è un enorme miglioramento per gli sviluppatori web. Molte delle attività eseguite sul server richiedono molto tempo.
Inviando in modo asincrono, JavaScript non deve attendere la risposta del server, ma può invece:
- eseguire altri script in attesa della risposta del server
- gestire la risposta quando la risposta è pronta
Asincrono = vero
Quando si utilizza async = true, specificare una funzione da eseguire quando la risposta è pronta nell'evento onreadystatechange:
Esempio
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "xmlhttp_info.txt", true);
xmlhttp.send();
Asincrono = falso
Per usare async = false, cambia il terzo parametro nel metodo open() su false:
xmlhttp.open("GET", "xmlhttp_info.txt", false);
L'uso di async = false non è consigliato, ma per alcune piccole richieste può andare bene.
Ricorda che JavaScript NON continuerà a essere eseguito, finché la risposta del server non sarà pronta. Se il server è occupato o lento, l'applicazione si bloccherà o si arresterà.
Nota: quando usi async = false, NON scrivere una funzione onreadystatechange - inserisci semplicemente il codice dopo l'istruzione send():
Esempio
xmlhttp.open("GET", "xmlhttp_info.txt", false);
xmlhttp.send();
document.getElementById("demo").innerHTML = xmlhttp.responseText;
Analizzatore XML
Tutti i browser moderni hanno un parser XML integrato.
L'XML Document Object Model (il DOM XML) contiene molti metodi per accedere e modificare XML.
Tuttavia, prima di poter accedere a un documento XML, è necessario caricarlo in un oggetto DOM XML.
Un parser XML può leggere testo normale e convertirlo in un oggetto DOM XML.
Analisi di una stringa di testo
Questo esempio analizza una stringa di testo in un oggetto DOM XML ed estrae le informazioni da esso con JavaScript:
Esempio
<html>
<body>
<p id="demo"></p>
<script>
var text, parser,
xmlDoc;
text = "<bookstore><book>" +
"<title>Everyday
Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
Vecchi browser (IE5 e IE6)
Le versioni precedenti di Internet Explorer (IE5 e IE6) non supportano l'oggetto XMLHttpRequest.
Per gestire IE5 e IE6, controlla se il browser supporta l'oggetto XMLHttpRequest, oppure crea un ActiveXObject:
Esempio
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Le versioni precedenti di Internet Explorer (IE5 e IE6) non supportano l'oggetto DOMPaser.
Per gestire IE5 e IE6, controlla se il browser supporta l'oggetto DOMPaser, oppure crea un ActiveXObject:
Esempio
if (window.DOMParser) {
// code for modern browsers
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
}
else {
// code for old IE browsers
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(text);
}
Altri esempi
Recupera le informazioni sull'intestazione di una risorsa (file).
Recupera informazioni di intestazione specifiche di una risorsa (file).
Come una pagina Web può comunicare con un server Web mentre un utente digita i caratteri in un campo di input.
Come una pagina Web può recuperare informazioni da un database con l'oggetto XMLHttpRequest.
Creare un XMLHttpRequest per recuperare i dati da un file XML e visualizzare i dati in una tabella HTML.