AJAX - XMLHttpRequest-objekt

XMLHttpRequest-objektet är grunden för AJAX.

  1. Skapa XMLHttpRequest-objekt
  2. Definiera callback-funktion
  3. Öppna XMLHttpRequest-objektet
  4. Skicka en förfrågan till servern

XMLHttpRequest-objekt

Alla moderna webbläsare stöder XMLHttpRequest-objekt.

XMLHttpRequest-objektet kan användas för att utbyta data med webbservern i bakgrunden. Detta innebär att delar av webbsidan kan uppdateras utan att hela sidan behöver laddas om.

Skapa XMLHttpRequest-objekt

Alla moderna webbläsare (Chrome, Firefox, IE, Edge, Safari, Opera) har inbyggda XMLHttpRequest-objekt.

Syntax för att skapa XMLHttpRequest-objekt:

variable = new XMLHttpRequest();

Definiera callback-funktion

Callback-funktion är en funktion som skickas som parameter till en annan funktion.

I detta fall bör callback-funktionen innehålla koden som ska köras när svaret är klart.

xhttp.onload = function() {
  // Vad som ska göras när svaret är klart
}

Skicka förfrågan

För att skicka en förfrågan till servern kan du använda XMLHttpRequest-objektets open() och send() Metod:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Exempel

// Skapa XMLHttpRequest-objekt
const xhttp = new XMLHttpRequest();
// Definiera callback-funktion
xhttp.onload = function() {
  // Du kan använda data här
}
// Skicka förfrågan
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Prova själv

Överskjutande domänåtkomst (Access Across Domains)

Av säkerhetsskäl tillåter moderna webbläsare inte överskjutande domänåtkomst.

Detta innebär att webbsidan och den XML-fil den försöker ladda in måste vara på samma server.

Exempel på CodeW3C.com öppnar XML-filer som finns inom CodeW3C.com-domänen.

Om du vill använda ett av de exempel på din webbsida, måste den XML-fil du laddar in vara på din egen server.

XMLHttpRequest-objektets metoder

Metod Description
new XMLHttpRequest() Skapa ett nytt XMLHttpRequest-objekt.
abort() Avbryt den aktuella förfrågan.
getAllResponseHeaders() Returnera headerinformation.
getResponseHeader() Returnera specifik headerinformation.
open(method, url, async, user, psw)

Definiera förfrågan.

  • methodFörfrågningsTyp GET eller POST
  • urlFilposition
  • asynctrue (asynkron) eller false (synkron)
  • userValfritt användarnamn
  • pswValfritt lösenord
send() Skicka en förfrågan till servern, används för GET-förfrågningar.
send(string) Skicka en förfrågan till servern, används för POST-förfrågningar.
setRequestHeader() Lägg till etikett/värde-paar till de skickade rubrikerna.

XMLHttpRequest-objektets egenskaper

Property Description
onload Definiera en funktion som anropas när en (laddning) förfrågan mottas.
onreadystatechange Definiera en funktion som anropas när readyState-attributet förändras.
readyState

Save the XMLHttpRequest status.

  • 0: The request has not been initialized
  • 1: The server connection has been established
  • 2: The request has been received
  • 3: The request is being processed
  • 4: The request has been completed and the response is ready
responseText Return the response data as a string.
responseXML Return the response data in XML format.
status

Return the status number of the request

  • 200: "OK"
  • 403: "Forbidden"
  • 404: "Not Found"

For a complete list, please visit Http Message Reference Manual

statusText Return the status text (such as "OK" or "Not Found")

onload property

When using the XMLHttpRequest object, you can define a callback function to be executed when the response is received.

Please define a callback function in the XMLHttpRequest object: onload Define the function in the property:

Exempel

xhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Prova själv

Multiple callback functions

If there are multiple AJAX tasks on the website, a function to execute the XMLHttpRequest object should be created, and a callback function should be created for each AJAX task.

The function call should include the URL and the function to be called when the response is ready.

Exempel

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) {
  // This is the action
}
function myFunction2(xhttp) {
  // This is the action
}

onreadystatechange property

readyState Property saves the status of XMLHttpRequest.

onreadystatechange Property defines a callback function to be executed when the readyState changes.

status Property and statusText Property saves the status of the XMLHttpRequest object.

Property Description
onreadystatechange Define the function to be called when the readyState property changes.
readyState

Save the XMLHttpRequest status.

  • 0: The request has not been initialized
  • 1: The server connection has been established
  • 2: The request has been received
  • 3: The request is being processed
  • 4: The request has been completed and the response is ready
status

Return the status number of the request

  • 200: "OK"
  • 403: "Forbidden"
  • 404: "Not Found"

For a complete list, please visit Http Message Reference Manual

statusText statusText

Returnerar status-texten (t.ex. "OK" eller "Not Found").

Varje gång readyState ändras anropas onreadystatechange-funktionen. 4 och status är 200 När, svar är klart:

Exempel

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();
}

Prova själv

onreadystatechange-händelsen utlöstes fyra gånger (1-4), varje gång readyState ändrades en gång.