AJAX - Respuesta del servidor
La propiedad onreadystatechange
La propiedad readyState contiene el estado de XMLHttpRequest.
La propiedad onreadystatechange define una función que se ejecutará cuando cambie readyState.
La propiedad de estado y la propiedad statusText contienen el estado del objeto 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 función onreadystatechange se llama cada vez que cambia readyState.
Cuando readyState es 4 y el estado es 200, la respuesta está lista:
Ejemplo
function loadDoc() {
var 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", true);
xhttp.send();
}
El archivo "ajax_info.txt" utilizado en el ejemplo anterior es un archivo de texto simple y se ve así:
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a
technique for accessing web servers from a web page.</p>
<p>AJAX stands for
Asynchronous JavaScript And XML.</p>
El evento onreadystatechange se activa cuatro veces (1-4), una vez por cada cambio en readyState.
Uso de una función de devolución de llamada
Una función de devolución de llamada es una función que se pasa como parámetro a otra función.
Si tiene más de una tarea AJAX en un sitio web, debe crear una función para ejecutar el objeto XMLHttpRequest y una función de devolución de llamada para cada tarea AJAX.
La llamada a la función debe contener la URL y qué función llamar cuando la respuesta esté lista.
Ejemplo
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
Propiedades de respuesta del servidor
Property | Description |
---|---|
responseText | get the response data as a string |
responseXML | get the response data as XML data |
Métodos de respuesta del servidor
Method | Description |
---|---|
getResponseHeader() | Returns specific header information from the server resource |
getAllResponseHeaders() | Returns all the header information from the server resource |
La propiedad de texto de respuesta
La propiedad responseText devuelve la respuesta del servidor como una cadena de JavaScript y puede usarla en consecuencia:
Ejemplo
document.getElementById("demo").innerHTML = xhttp.responseText;
La propiedad responseXML
El objeto XML HttpRequest tiene un analizador XML incorporado.
La propiedad responseXML devuelve la respuesta del servidor como un objeto DOM XML.
Con esta propiedad, puede analizar la respuesta como un objeto DOM XML:
Ejemplo
Solicite el archivo cd_catalog.xml y analice la respuesta:
xmlDoc = xhttp.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;
xhttp.open("GET",
"cd_catalog.xml", true);
xhttp.send();
Aprenderá mucho más sobre XML DOM en los capítulos DOM de este tutorial.
El método getAllResponseHeaders()
El método getAllResponseHeaders() devuelve toda la información del encabezado de la respuesta del servidor.
Ejemplo
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};
El método getResponseHeader()
El método getResponseHeader() devuelve información de encabezado específica de la respuesta del servidor.
Ejemplo
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();