AJAX - Objeto XMLHttpRequest

El objeto XMLHttpRequest es la base de AJAX.

  1. Create XMLHttpRequest object
  2. Define callback function
  3. Abrir el objeto XMLHttpRequest
  4. Enviar solicitudes al servidor

XMLHttpRequest object

Todos los navegadores modernos lo soportan XMLHttpRequest object.

El objeto XMLHttpRequest se puede utilizar para intercambiar datos con el servidor web en segundo plano. Esto significa que se puede actualizar parte del contenido de la página web sin recargar toda la página.

Create XMLHttpRequest object

All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Define callback function

A callback function is a function that is passed as a parameter to another function.

In this case, the callback function should contain the code to be executed when the response is ready.

xhttp.onload = function() {
  // What to do when the response is ready
}

Send request

To send a request to the server, you can use the XMLHttpRequest object's open() and send() Method:

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

Ejemplo

// Create XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define callback function
xhttp.onload = function() {
  // You can use data here
}
// Send request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Pruebe usted mismo

Cross-domain access (Access Across Domains)

For security reasons, modern browsers do not allow cross-domain access.

This means that the web page and the XML file it tries to load must be on the same server.

Examples on CodeW3C.com all open XML files located in the CodeW3C.com domain.

If you want to use the above example on one of your web pages, the XML file you load must be located on your own server.

XMLHttpRequest object methods

Method Descripción
new XMLHttpRequest() Create a new XMLHttpRequest object.
abort() Cancel the current request.
getAllResponseHeaders() Return header information.
getResponseHeader() Return specific header information.
open(method, url, async, user, psw)

Specify the request.

  • method: request type GET or POST
  • url: file location
  • async: true (asynchronous) or false (synchronous)
  • user: optional username
  • psw: optional password
send() Send a request to the server, used for GET requests.
send(string) Send a request to the server, used for POST requests.
setRequestHeader() Add a label/value pair to the headers to be sent.

XMLHttpRequest object attributes

Atributo Descripción
onload Define the function to be called when a (loading) request is received.
onreadystatechange Define the function to be called when the readyState attribute changes.
readyState

Guarda el estado de XMLHttpRequest

  • 0: La solicitud no se ha inicializado
  • 1: Se ha establecido la conexión del servidor
  • 2: La solicitud se ha recibido
  • 3: Se está procesando la solicitud
  • 4: La solicitud se ha completado y la respuesta está lista
responseText Devuelve los datos de respuesta en forma de cadena
responseXML Devuelve los datos de respuesta en formato XML
estado

Devuelve el número de estado de la solicitud

  • 200: "OK"
  • 403: "Prohibido"
  • 404: "No encontrado"

Para obtener una lista completa, visite Manual de referencia de mensaje HTTP

statusText Devuelve el texto de estado (por ejemplo, "OK" o "Not Found")

Atributo onload

Al usar el objeto XMLHttpRequest, puede definir una función de devolución de llamada para ejecutar cuando se reciba la respuesta de la solicitud

Por favor, define la función en el objeto XMLHttpRequest onload La función se define en el atributo

Ejemplo

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

Pruebe usted mismo

Múltiples funciones de devolución de llamada

Si hay múltiples tareas AJAX en el sitio web, debe crear una función que ejecute el objeto XMLHttpRequest y crear una función de devolución de llamada para cada tarea AJAX

La llamada a la función debe incluir la URL y la función que se debe llamar cuando la respuesta esté lista

Ejemplo

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) {
  // Aquí está la acción
}
function myFunction2(xhttp) {
  // Aquí está la acción
}

Atributo onload

readyState Atributo que guarda el estado de XMLHttpRequest

onreadystatechange Atributo que define una función de devolución de llamada que se ejecuta cuando cambia el readyState

estado Atributo y statusText Atributo que guarda el estado del objeto XMLHttpRequest

Atributo Descripción
onreadystatechange Define la función que se llama cuando cambia el atributo readyState
readyState

Guarda el estado de XMLHttpRequest

  • 0: La solicitud no se ha inicializado
  • 1: Se ha establecido la conexión del servidor
  • 2: La solicitud se ha recibido
  • 3: Se está procesando la solicitud
  • 4: La solicitud se ha completado y la respuesta está lista
estado

Devuelve el número de estado de la solicitud

  • 200: "OK"
  • 403: "Prohibido"
  • 404: "No encontrado"

Para obtener una lista completa, visite Manual de referencia de mensaje HTTP

statusText statusText

Devuelve el texto de estado (por ejemplo, "OK" o "No encontrado").

El función onreadystatechange se llama cada vez que cambia el readyState. 4 y status sea 200 Cuando la respuesta esté lista:

Ejemplo

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

Pruebe usted mismo

El evento onreadystatechange se activó cuatro veces (1-4), cambiando el readyState cada vez.