Esercitazione JS

JS CASA JS Introduzione JS Dove si va Uscita JS Dichiarazioni JS Sintassi JS Commenti JS Variabili JS JS Let JS Cost Operatori JS JS aritmetica Assegnazione JS Tipi di dati JS Funzioni JS Oggetti JS Eventi JS Corde JS Metodi di stringa JS Ricerca di stringhe JS Modelli di stringhe JS Numeri JS Metodi numerici JS Matrici JS Metodi array JS Ordinamento matrice JS Iterazione dell'array JS Cost. array JS Date JS Formati data JS Metodi di acquisizione della data JS Metodi di impostazione della data JS JS matematica JS Casuale JS booleani Confronti JS Condizioni JS JS Switch Ciclo JS per JS Loop per In Ciclo JS per di JS Loop mentre JS Break Iterabili JS Insiemi JS Mappe JS Tipo JS Conversione del tipo JS JS bit a bit JS RegExp Errori JS Ambito JS JS sollevamento Modalità rigorosa JS JS questa parola chiave Funzione freccia JS Classi JS JS JSON Debug JS Guida allo stile JS Migliori Pratiche JS Errori di JS Prestazioni JS Parole riservate JS

Versioni JS

Versioni JS JS 2009 (ES5) JS 2015 (ES6) JS 2016 JS 2017 JS 2018 JS IE / Edge Storia di JS

Oggetti JS

Definizioni di oggetti Proprietà dell'oggetto Metodi dell'oggetto Visualizzazione di oggetti Accessori per oggetti Costruttori di oggetti Prototipi di oggetti Iterabili di oggetti Insiemi di oggetti Mappe degli oggetti Riferimento all'oggetto

Funzioni JS

Definizioni delle funzioni Parametri di funzione Invocazione di funzione Chiamata di funzione Funzione Applica Chiusure di funzioni

Classi JS

Introduzione alla classe Eredità di classe Classe statica

JS Async

Richiamate JS JS asincrono JS Promesse JS Async/Attendere

JS HTML DOM

DOM Introduzione Metodi DOM Documento DOM Elementi DOM DOM HTML Moduli DOM DOM CSS Animazioni DOM Eventi DOM Ascoltatore di eventi DOM Navigazione DOM Nodi DOM Collezioni DOM Elenchi di nodi DOM

Distinta base del browser JS

Finestra JS Schermo JS Posizione JS Storia di JS Navigatore JS Avviso popup JS JS tempismo Biscotti JS

API Web JS

Introduzione all'API Web API dei moduli Web API Cronologia web API di archiviazione Web API Web Worker API di recupero Web API di geolocalizzazione web

JS AJAX

Introduzione all'Ajax AJAX XMLHttp Richiesta AJAX Risposta dell'AJAX File XML AJAX AJAX PHP AJAX ASP Database AJAX Applicazioni AJAX Esempi AJAX

JS JSON

Introduzione JSON Sintassi JSON JSON contro XML Tipi di dati JSON Analisi JSON JSON Stringify Oggetti JSON Matrici JSON Server JSON JSON PHP JSON HTML JSON JSONP

JS vs jQuery

Selettori jQuery jQuery HTML jQuery CSS jQuery DOM

Grafica JS

Grafica JS Tela JS JS Plotly JS Chart.js Grafico di Google JS JS D3.js

Esempi JS

Esempi JS JS HTML DOM Input HTML JS Oggetti HTML JS Eventi HTML JS Browser JS Editore JS Esercizi JS Quiz J.S Certificato JS

Riferimenti JS

Oggetti JavaScript Oggetti HTML DOM


AJAX - L'oggetto XMLHttpRequest

La chiave di volta di AJAX è l'oggetto XMLHttpRequest.

  1. Creare un oggetto XMLHttpRequest
  2. Definire una funzione di richiamata
  3. Aprire l'oggetto XMLHttpRequest
  4. Invia una richiesta a un server

L'oggetto XMLHttpRequest

Tutti i browser moderni supportano l' XMLHttpRequestoggetto.

L' XMLHttpRequestoggetto 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 XMLHttpRequestoggetto integrato.

Sintassi per creare un XMLHttpRequestoggetto:

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() XMLHttpRequestdell'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' XMLHttpRequestoggetto è possibile definire una funzione di callback da eseguire quando la richiesta riceve una risposta.

La funzione è definita nella onloadproprietà XMLHttpRequestdell'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 XMLHttpRequestdell'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 readyStateproprietà mantiene lo stato di XMLHttpRequest.

La onreadystatechangeproprietà definisce una funzione di callback da eseguire quando readyState cambia.

La statusproprietà e le statusTextproprietà 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 onreadystatechangefunzione 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' onreadystatechangeevento viene attivato quattro volte (1-4), una volta per ogni modifica in readyState.