AJAX - L'oggetto XMLHttpRequest
La chiave di volta di AJAX è l'oggetto XMLHttpRequest.
- Creare un oggetto XMLHttpRequest
- Definire una funzione di richiamata
- Aprire l'oggetto XMLHttpRequest
- Invia una richiesta a un server
L'oggetto XMLHttpRequest
Tutti i browser moderni supportano l' XMLHttpRequest
oggetto.
L' XMLHttpRequest
oggetto può essere utilizzato per scambiare dati con un server Web dietro le quinte. Ciò significa che è possibile aggiornare parti di una pagina web, senza ricaricare l'intera pagina.
Creare un oggetto XMLHttpRequest
Tutti i browser moderni (Chrome, Firefox, IE, Edge, Safari, Opera) hanno un XMLHttpRequest
oggetto integrato.
Sintassi per creare un XMLHttpRequest
oggetto:
variable = new XMLHttpRequest();
Definire una funzione di richiamata
Una funzione di callback è una funzione passata come parametro a un'altra funzione.
In questo caso, la funzione di callback dovrebbe contenere il codice da eseguire quando la risposta è pronta.
xhttp.onload = function() {
// What to do when the response is ready
}
Invia una richiesta
Per inviare una richiesta a un server, puoi utilizzare i metodi open() e send()
XMLHttpRequest
dell'oggetto:
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Esempio
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function
xhttp.onload = function() {
// Here you can use the Data
}
// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
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.
Metodi dell'oggetto XMLHttpRequest
Method | Description |
---|---|
new XMLHttpRequest() | Creates a new XMLHttpRequest object |
abort() | Cancels the current request |
getAllResponseHeaders() | Returns header information |
getResponseHeader() | Returns specific header information |
open(method, url, async, user, psw) | Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password |
send() | Sends the request to the server Used for GET requests |
send(string) | Sends the request to the server. Used for POST requests |
setRequestHeader() | Adds a label/value pair to the header to be sent |
Proprietà dell'oggetto XMLHttpRequest
Property | Description |
---|---|
onload | Defines a function to be called when the request is recieved (loaded) |
onreadystatechange | Defines a function to be called when the readyState property changes |
readyState | Holds 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 |
responseText | Returns the response data as a string |
responseXML | Returns the response data as XML data |
status | Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |
La proprietà di caricamento
Con l' XMLHttpRequest
oggetto è possibile definire una funzione di callback da eseguire quando la richiesta riceve una risposta.
La funzione è definita nella onload
proprietà XMLHttpRequest
dell'oggetto:
Esempio
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Molteplici funzioni di richiamata
Se si dispone di più attività AJAX in un sito Web, è necessario creare una funzione per l'esecuzione XMLHttpRequest
dell'oggetto e una funzione di callback per ciascuna attività AJAX.
La chiamata di funzione dovrebbe contenere l'URL e quale funzione chiamare quando la risposta è pronta.
Esempio
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
La proprietà onreadystatechange
La readyState
proprietà mantiene lo stato di XMLHttpRequest.
La onreadystatechange
proprietà definisce una funzione di callback da eseguire quando readyState cambia.
La status
proprietà e le statusText
proprietà mantengono lo stato dell'oggetto XMLHttpRequest.
Property | Description |
---|---|
onreadystatechange | Defines a function to be called when the readyState property changes |
readyState | Holds 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" 403: "Forbidden" 404: "Page not found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |
La onreadystatechange
funzione viene chiamata ogni volta che readyState cambia.
Quando readyState
è 4 e lo stato è 200, la risposta è pronta:
Esempio
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}
L' onreadystatechange
evento viene attivato quattro volte (1-4), una volta per ogni modifica in readyState.