From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- files/es/web/api/xmlhttprequest/abort/index.html | 120 ++++++ .../es/web/api/xmlhttprequest/formdata/index.html | 84 ++++ files/es/web/api/xmlhttprequest/index.html | 428 ++++++++++++++++++++ .../xmlhttprequest/onreadystatechange/index.html | 109 +++++ .../web/api/xmlhttprequest/responsetext/index.html | 104 +++++ .../index.html | 232 +++++++++++ files/es/web/api/xmlhttprequest/timeout/index.html | 67 +++ .../xmlhttprequest/using_xmlhttprequest/index.html | 447 +++++++++++++++++++++ 8 files changed, 1591 insertions(+) create mode 100644 files/es/web/api/xmlhttprequest/abort/index.html create mode 100644 files/es/web/api/xmlhttprequest/formdata/index.html create mode 100644 files/es/web/api/xmlhttprequest/index.html create mode 100644 files/es/web/api/xmlhttprequest/onreadystatechange/index.html create mode 100644 files/es/web/api/xmlhttprequest/responsetext/index.html create mode 100644 files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html create mode 100644 files/es/web/api/xmlhttprequest/timeout/index.html create mode 100644 files/es/web/api/xmlhttprequest/using_xmlhttprequest/index.html (limited to 'files/es/web/api/xmlhttprequest') diff --git a/files/es/web/api/xmlhttprequest/abort/index.html b/files/es/web/api/xmlhttprequest/abort/index.html new file mode 100644 index 0000000000..de73cb1a5d --- /dev/null +++ b/files/es/web/api/xmlhttprequest/abort/index.html @@ -0,0 +1,120 @@ +--- +title: XMLHttpRequest.abort() +slug: Web/API/XMLHttpRequest/abort +tags: + - AJAX + - API + - HTTP + - HttpRequest + - Referencia + - XHR + - XMLHttpRequest + - abortar + - metodo +translation_of: Web/API/XMLHttpRequest/abort +--- +

{{APIRef('XMLHttpRequest')}}

+ +

El método XMLHttpRequest.abort() aborta la petición si ha sido enviada. Cuando una petición se aborta, readyState se asigna a 0 (UNSENT), pero el evento readystatechange no se lanza.

+ +

Sintaxis

+ +
xhrInstance.abort();
+ +

Parámetros

+ +

Ninguno.

+ +

Valor de retorno

+ +

Vacío.

+ +

Ejemplo

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+xhr.open(method,url,true);
+
+xhr.send();
+
+xhr.abort();
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('XMLHttpRequest', '#the-abort()-method')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
MejoraChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte básico{{CompatChrome(1)}}{{CompatUnknown}}{{CompatIe('5')}}[1]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
MejoraAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This feature was implemented via ActiveXObject(). Internet Explorer implementa el estándar XMLHttpRequest desde la versión 7.

+ +

Ver también

+ + diff --git a/files/es/web/api/xmlhttprequest/formdata/index.html b/files/es/web/api/xmlhttprequest/formdata/index.html new file mode 100644 index 0000000000..2ca830daf7 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/formdata/index.html @@ -0,0 +1,84 @@ +--- +title: FormData +slug: Web/API/XMLHttpRequest/FormData +tags: + - API + - FormData + - Interfaz + - Referencia + - XMLHttpRequest +translation_of: Web/API/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

La interfaz FormData proporciona una manera sencilla de construir un conjunto de parejas clave/valor que representan los campos de un formulario y sus valores, que pueden ser enviados fácilmente con el método {{domxref("XMLHttpRequest.send()")}}. Utiliza el mismo formato que usaría un formulario si el tipo de codificación fuera "multipart/form-data".

+ +

También puede pasarse directamente al constructor de {{domxref("URLSearchParams")}} si se quieren generar parámetros de consulta de la misma forma en que lo haría un {{HTMLElement("form")}} si usara un envío GET simple.

+ +

Un objeto que implementa FormData puede usarse directamente en una estructura {{jsxref("Statements/for...of", "for...of")}}, en lugar de {{domxref('FormData.entries()', 'entries()')}}: for (var p of myFormData) es equivalente a for (var p of myFormData.entries()).

+ +
+

Nota: Esta característica está disponible en Web Workers.

+
+ +

Constructor

+ +
+
{{domxref("FormData.FormData","FormData()")}}
+
Crea un nuevo objeto FormData.
+
+ +

Métodos

+ +
+
{{domxref("FormData.append()")}}
+
Agrega un nuevo valor a una clave existente dentro de un objeto FormData, o añade la clave si aún no existe.
+
{{domxref("FormData.delete()")}}
+
Elimina una pareja clave/valor de un objeto FormData.
+
{{domxref("FormData.entries()")}}
+
Devuelve un {{jsxref("Iteration_protocols","iterator")}} que permite recorrer todas las parejas clave/valor contenidas en este objeto.
+
{{domxref("FormData.get()")}}
+
Devuelve el primer valor asociado con una clave dada en un objeto FormData.
+
{{domxref("FormData.getAll()")}}
+
Devuelve un array con todos los valores asociados con una clave dada en un objeto FormData.
+
{{domxref("FormData.has()")}}
+
Devuelve un booleano que indica si un objeto FormData contiene una clave determinada.
+
{{domxref("FormData.keys()")}}
+
Devuelve un {{jsxref("Iteration_protocols", "iterator")}} que permite recorrer todas las claves de las parejas clave/valor contenidas en este objeto.
+
{{domxref("FormData.set()")}}
+
Establece un nuevo valor para una clave existente dentro de un objeto FormData, o agrega la clave/valor si aún no existe.
+
{{domxref("FormData.values()")}}
+
Devuelve un {{jsxref("Iteration_protocols", "iterator")}} que permite recorrer todos los valores contenidos en este objeto.
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}{{Spec2('XMLHttpRequest')}}FormData definido en XHR spec
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("api.FormData")}}

+ +

Ver también

+ + diff --git a/files/es/web/api/xmlhttprequest/index.html b/files/es/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..243b3220e6 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/index.html @@ -0,0 +1,428 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - Todas_las_Categorías + - XMLHttpRequest + - páginas_a_traducir +translation_of: Web/API/XMLHttpRequest +--- +

XMLHttpRequest es un objeto JavaScript que fue diseñado por Microsoft y adoptado por Mozilla, Apple y Google. Actualmente es un estándar de la W3C. Proporciona una forma fácil de obtener información de una URL sin tener que recargar la página completa. Una página web puede actualizar sólo una parte de la página sin interrumpir lo que el usuario está haciendo. XMLHttpRequest es ampliamente usado en la programación AJAX.

+ +

A pesar de su nombre, XMLHttpRequest puede ser usado para recibir cualquier tipo de dato, no solo XML, y admite otros formatos además de HTTP (incluyendo file y ftp).

+ +

Para crear una instancia de XMLHttpRequest, debes hacer lo siguiente:

+ +
var req = new XMLHttpRequest();
+
+ +

Para obtener más información de cómo usar XMLHttpRequest, mira Usar XMLHttpRequest.

+ +
Nota: De forma predeterminada, Firefox 3 limita la cantidad de conexiones de XMLHttpRequest por servidor a 6 (las versiones previas limitan a 2 conexiones por servidor). Algunos sitios web interactivos pueden mantener una conexión XMLHttpRequest abierta, así que abrir múltiples sesiones a esos sitios puede derivar en congelamientos del navegador de una forma que la ventana no se actualiza y los controles no responden. Este valor puede ser cambiado al editar la preferencia network.http.max-persistent-connections-per-server en about:config.
+ +

Resumen del método

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void abort();
string getAllResponseHeaders();
ACString getResponseHeader(in AUTF8String header);
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);
void open(in AUTF8String method, in AUTF8String url);
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void overrideMimeType(in AUTF8String mimetype);
void send([optional] in nsIVariant body);
void sendAsBinary(in DOMString body); {{ fx_minversion_inline(3) }}
void setRequestHeader(in AUTF8String header, in AUTF8String value);
+ +

Propiedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AtributoTipoDescripción
channel{{ Interface("nsIChannel") }}El canal es usado por el objeto cuando se produce el pedido. Esto da null si el canal aún no fue creado. En el caso de un pedido de múltiples partes, este es el canal inicial, no las diferentes partes del pedido múltiple. Es necesario tener privilegios elevados para acceder; sólo lectura. {{ Non-standard_inline() }}
mozBackgroundRequestbooleano +

Indica si el objeto representa o no un pedido de un servicio de fondo. Si es true, no se asocia una carga de grupo con el pedido, y los diálogos de seguridad no se muestran al usuario. Es necesario tener privilegios elevados para acceder. {{ Non-standard_inline() }}

+ +

En los casos en que un diálogo de seguridad debe ser mostrado (como en una autentficación o la notificación de un certificado no válido), el pedido simplemente falla.

+
mozResponseArrayBuffer  {{ non-standard_inline() }}ArrayBufferLa respuesta al pedido en la forma de un arreglo de JavaScript. Esto es NULL si el pedido no fue exitoso o si todavía no ha sido enviado. Sólo lectura.
multipartbooleano +

Indica cuando se espera que la respuesta sea o no una serie de mútiples documentos XML. Si se define como true, el tipo de contenido de la respuesta inicial debe ser multipart/x-mixed-replace u ocurrirá un error. Todos los pedidos deben ser asincrónicos.

+ +

Esto permite el uso del push del servidor; para cada documento XML que se escribe para este pedido, se crea un nuevo XMLDOMdocument y se llama al manejador onload entre cada documento.

+ +
Nota: Cuando esto se elige, el manejador onload y otros manejadores de eventos no son reiniciados después de que el primer XMLdocument es cargado, y el manejador onload es llamado después de que cada parte de la respuesta es recibida.
+
+

onreadystatechange

+
{{ Interface("nsIDOMEventListener") }} +

Una función del objeto JavaScript que se llama cuando el atributo readyState cambia. El callback se llama desde la interfaz del usuario.

+ +
Aviso: Esto no debe ser usado desde código nativo. Tampoco debes usarlo con pedidos sincrónicos.
+
readyStatelong +

El estado del pedido:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorEstadoDescripción
0UNINITIALIZEDtodavía no se llamó a open().
1LOADINGtodavía no se llamó a send().
2LOADEDsend() ya fue invocado, y los encabezados y el estado están disponibles.
3INTERACTIVEDescargando; responseText contiene información parcial.
4COMPLETEDLa operación está terminada.
+
responseTextAStringLa respuesta al pedido como texto, o null si el pedido no fue exitoso o todavía no se envió. Sólo lectura.
responseXMLnsIDOMDocument +

La respuesta al pedido como un objeto DOMDocument, o null si el pedido no fue exitoso, aún no fue enviado o no puede ser analizado como XML. La respuesta es analizada como si fuera text/xml. Sólo lectura.

+ +
Nota: Si el servidor no aplica el encabezado de tipo de contenido text/xml, puedes usar overrideMimeType() para forzar a XMLHttpRequest a analizarlo como XML igualmente.
+
statusunsigned longEl estado de la respuesta al pedido. Éste es el código HTTPresult (por ejemplo, status es 200 por un pedido exitoso). Sólo lectura.
statusTextAUTF8StringLa cadena de respuesta que devuelve el HTTPserver. A diferencia de status, este incluye el texto completo del mensaje de respuesta ("200 OK", por ejemplo). Sólo lectura.
upload{{ Interface("nsIXMLHttpRequestUpload") }}El proceso de subida puede ser rastreado al agregar un registro de evento a upload. {{ fx_minversion_inline(3.5) }}
withCredentialsbooleano +

Indica cuando el pedido de Access-Control entre sitios debe o no ser realizado usando credenciales como cookies o encabezados de autorización. {{ fx_minversion_inline(3.5) }}

+ +
Nota: Esto nunca afecta los pedidos en para el propio sitio.
+ +

El valor predeterminado es false.

+
+ +

Métodos

+ +

abort()

+ +

Aborta el pedido si éste ya fue enviado.

+ +
void abort();
+
+ +
Parámetros
+ +

Ninguno.

+ +

getAllResponseHeaders()

+ +

Devuelve todos los encabezados de respuesta como una cadena.

+ +
Nota: Para pedidos multi partes, esto devuelve los encabezados de la parte actual del pedido, no del canal original.
+ +
string getAllResponseHeaders();
+
+ +
Parámetros
+ +

Ninguno.

+ +
Valor devuelto
+ +

El texto de todos los encabezados de respuesta, o null si no se ha recibido ninguna respuesta.

+ +

getResponseHeader()

+ +

Devuelve el texto de un encabezado específico.

+ +
ACString getResponseHeader(
+ in AUTF8String header
+);
+
+ +
Parámetros
+ +
+
header
+
El nombre del encabezado buscado.
+
+ +
Valor devuelto
+ +

Una cadena que contiene el texto de un encabezado específico, o null tanto si la respuesta no se ha recibido o el encabezado no existe en la respuesta.

+ +

init()

+ +

Inicializa el objeto para que sea usado desde código C++.

+ +
Aviso: Este método no debe ser llamado desde JavaScript.
+ +
[noscript] void init(
+ in nsIPrincipal principal,
+ in nsIScriptContext scriptContext,
+ in nsPIDOMWindow ownerWindow
+);
+
+ +
Parámetros
+ +
+
principal
+
El principal para usar en el pedido; no debe ser null.
+
scriptContext
+
El contexto del programa que usará en el pedido; no debe ser null.
+
ownerWindow
+
La ventana asociada con el pedido; puede ser null.
+
+ +

open()

+ +

Inicializa el pedido. Este método es para ser usado desde código JavaScript, para inicializar un pedido desde código nativo, debes usar openRequest().

+ +
Nota: Llamar a este método en un pedido activo (uno para el cual open() o openRequest() ya han sido llamados) es equivalente a usar abort().
+ +
void open(
+ in AUTF8String method,
+ in AUTF8String url,
+ [optional] in boolean async,
+ [optional] in AString user,
+ [optional] in AString password
+);
+
+ +
Parámetros
+ +
+
method
+
El método HTTP a usar: tanto "POST" o "GET". Se ignora para urls que no son de HTTP.
+
url
+
La URL a la que se envía el pedido.
+
async
+
Un parámetro booleano opcional, predeterminado es true, que indica si se debe o no realizar la operación de forma asíncrona. Si este valor es false, el método send() no se devuelve hasta que se reciba la respuesta completa. Si es true, la notificación de una transacción completada se proporciona mediante los oyentes de eventos. Esto debe ser true si el atributo multipart es verdadero o se lanzará una excepción.
+
user
+
El nombre de usuario es opcional solo es usado con fines de autenticación, de forma predeterminada es una cadena vacía.
+
password
+
La contraseña es opcional solo es usado con fines de autenticación, de forma predeterminada es una cadena vacía.
+
+ +

openRequest()

+ +

Inicia la peticion, este metodo est

+ +

Inicializa la peticion. Este método se utiliza desde el código nativo, para inicializar una solicitud desde el código JavaScript, utilice open () en su lugar.

+ +
Nota: Calling this method an already active request (one for which open()or openRequest()has already been called) is the equivalent of calling abort().
+ +
void open(
+ in AUTF8String method,
+ in AUTF8String url,
+ in boolean async,
+ in AString user,
+ in AString password
+);
+
+ +
Parameters
+ +
+
method
+
The HTTPmethod to use; either "POST"or "GET". Ignored for non-HTTPURLs.
+
url
+
The URLto which to send the request.
+
async
+
An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send()method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown.
+
user
+
The optional user name to use for authentication purposes; by default, this is an empty string.
+
password
+
The optional password to use for authentication purposes; by default, this is an empty string.
+
+ +

overrideMimeType()

+ +

Overrides the MIMEtype returned by the server.

+ +
Note: This method must be called before send().
+ +
void overrideMimeType(
+ in AUTF8String mimetype
+);
+
+ +
Parameters
+ +
+
mimetype
+
The type that should be used instead of the one returned by the server, if any.
+
+ +

send()

+ +

Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. If the request is synchronous, this method doesn't return until the response has arrived.

+ +
Note: Any event listeners you wish to set must be set before calling send().
+ +
void send(
+ [optional] in nsIVariant body
+);
+
+ +
Parameters
+ +
+
body
+
This may be an nsIDocument, nsIInputStream, or a string (an nsISupportsString if called from native code) that is used to populate the body of a POST request. Starting with Gecko 1.9.2, you may also specify an DOM{{ domxref("File") }} , and starting with Gecko 2.0 {{ geckoRelease("2.0") }} you may also specify a FormData object.
+
+ +
Notes
+ +

If the body is an nsIDOMDocument, it is serialized before being sent.

+ +

If it's an nsIInputStream, it must be compatible with nsIUploadChannel's setUploadStream()method. In that case, a Content-Length header is added to the request, with its value obtained using nsIInputStream's available()method. Any headers included at the top of the stream are treated as part of the message body. The stream's MIMEtype should be specified by setting the Content-Type header using the setRequestHeader()method prior to calling send().

+ +

sendAsBinary()

+ +

A variant of the send()method that sends binary data.

+ +
void sendAsBinary(
+ in DOMString body
+);
+
+ +
Parameters
+ +
+
body
+
The request body as a DOMstring. This data is converted to a string of single-byte characters by truncation (removing the high-order byte of each character).
+
+ +

setRequestHeader()

+ +

Sets the value of an HTTPrequest header.

+ +
Note: You must call open()before using this method.
+ +
void setRequestHeader(
+ in AUTF8String header,
+ in AUTF8String value
+);
+
+ +
Parameters
+ +
+
header
+
The name of the header whose value is to be set.
+
value
+
The value to set as the body of the header.
+
+ +

Implementation notes

+ +

XMLHttpRequest is implemented in Gecko using the {{ interface("nsIJSXMLHttpRequest") }} and {{ interface("nsIXMLHttpRequest") }} interfaces.

+ +

See also

+ + + +

{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "cn/XMLHttpRequest" } ) }}

diff --git a/files/es/web/api/xmlhttprequest/onreadystatechange/index.html b/files/es/web/api/xmlhttprequest/onreadystatechange/index.html new file mode 100644 index 0000000000..7f35ad3e88 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/onreadystatechange/index.html @@ -0,0 +1,109 @@ +--- +title: XMLHttpRequest.onreadystatechange +slug: Web/API/XMLHttpRequest/onreadystatechange +translation_of: Web/API/XMLHttpRequest/onreadystatechange +--- +
{{APIRef}}
+ +

Un EventHandler que es invocado cada vez que cambia el atributo readyState. La retrollamada (callback) es invocada desde el hilo (thread) perteneciente a la interfaz de usuario. La propiedad XMLHttpRequest.onreadystatechange contiene el manejador del evento que es invocado cuando se dispara el evento {{event("readystatechange")}}, lo cual sucede cada vez que cambia el valor de la propiedad {{domxref("XMLHttpRequest.readyState", "readyState")}} de {{domxref("XMLHttpRequest")}}. La retrollamada (callback) es invocada desde el hilo perteneciente a la interfaz de usuario.

+ +
+

Aviso: No debería ser usado con peticiones síncronas ni tampoco en código nativo.

+
+ +

El evento readystatechange no se disparará cuando una petición XMLHttpRequest sea cancelada mediante el método abort().

+ +

Sintaxis

+ +
XMLHttpRequest.onreadystatechange = callback;
+ +

Valores

+ + + +

Ejemplo

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+
+xhr.open(method, url, true);
+xhr.onreadystatechange = function () {
+        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
+            console.log(xhr.responseText);
+        }
+    };
+xhr.send();
+ +

Especificaciones

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#handler-xhr-onreadystatechange')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidad con navegadores Web

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{CompatGeckoDesktop(1.0)}}{{CompatIe(7)}}[1]{{CompatVersionUnknown}}{{CompatSafari(1.2)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Las versiones 5 y 6 admiten llamadas AJAX usando ActiveXObject().

diff --git a/files/es/web/api/xmlhttprequest/responsetext/index.html b/files/es/web/api/xmlhttprequest/responsetext/index.html new file mode 100644 index 0000000000..d119565243 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/responsetext/index.html @@ -0,0 +1,104 @@ +--- +title: XMLHttpRequest.responseText +slug: Web/API/XMLHttpRequest/responseText +translation_of: Web/API/XMLHttpRequest/responseText +--- +
{{draft}}
+ +
{{APIRef('XMLHttpRequest')}}
+ +

La propiedad XMLHttpRequest.responseText  devuelve un DOMString que contiene la  respuesta a la consulta como un texto o null si la consulta  no tuvo exito o  aun no ha sido completada. la propiedad responseText  tendra una respuesta parcial como retorno aunque la consulta no haya sido  completada. si responseType contiene algo que no sea un string vacio o un "text", el acceso a responseText sera throw InvalidStateError exception.

+ +

Ejemplo. Lanza  una excepción InvalidStateError

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+// If specified, responseType must be empty string or "text"
+xhr.responseType = 'text';
+
+xhr.onload = function () {
+    if (xhr.readyState === xhr.DONE) {
+        if (xhr.status === 200) {
+            console.log(xhr.response);
+            console.log(xhr.responseText);
+        }
+    }
+};
+
+xhr.send(null);
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificacionesestadoComentarios
{{SpecName('XMLHttpRequest', '#the-responsetext-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Anteriores a  IE 10, El valo de  XMLHttpRequest.responseText debe ser leido una vez que la consulta fuera completada.

diff --git a/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html new file mode 100644 index 0000000000..28675abd79 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html @@ -0,0 +1,232 @@ +--- +title: Solicitudes síncronas y asíncronas +slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +--- +

XMLHttpRequest soporta solicitudes síncronas y asíncronas, pero la mas preferida es la asíncrona por razones de rendimiento

+ +

Las solicitudes síncronas bloquean la ejecución del código, mientras se procesa la solicitud, dejando a la pantalla congelada y dando una experiencia de usuario poco agradable

+ +

Peticiones asíncronas

+ +

Si se utiliza XMLHttpRequest de forma asíncrona, recibirá una devolución de llamada cuando los datos se hayan recibido . Esto permite que el navegador continúe funcionando de forma normal mientras se procesa la solicitud.

+ +

Ejemplo: Enviar un archivo a la consola

+ +

Este es el uso más simple de la asíncronia XMLHttpRequest.

+ +
var xhr = new XMLHttpRequest();
+xhr.open("GET", "/bar/foo.txt", true);
+xhr.onload = function (e) {
+  if (xhr.readyState === 4) {
+    if (xhr.status === 200) {
+      console.log(xhr.responseText);
+    } else {
+      console.error(xhr.statusText);
+    }
+  }
+};
+xhr.onerror = function (e) {
+  console.error(xhr.statusText);
+};
+xhr.send(null); 
+ +

En la linea 2, el ultimo parametro de open() , especifica true para indicar que la solicitud se tratara de forma asíncrona

+ +

Line 3 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, dumps the received content.  If an error occurred, an error message is displayed.

+ +

Line 15 actually initiates the request.  The callback routine is called whenever the state of the request changes.

+ +

Ejemplo: Creando una funcion estandar para leer archivos externos.

+ +

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

+ +
function xhrSuccess () { this.callback.apply(this, this.arguments); }
+
+function xhrError () { console.error(this.statusText); }
+
+function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oReq = new XMLHttpRequest();
+  oReq.callback = fCallback;
+  oReq.arguments = Array.prototype.slice.call(arguments, 2);
+  oReq.onload = xhrSuccess;
+  oReq.onerror = xhrError;
+  oReq.open("get", sURL, true);
+  oReq.send(null);
+}
+
+ +

Usage:

+ +
function showMessage (sMsg) {
+  alert(sMsg + this.responseText);
+}
+
+loadFile("message.txt", showMessage, "New message!\n\n");
+
+ +

The signature of the utility function loadFile declares (i) a target URL to read (via HTTP GET), (ii) a function to execute on successful completion of the XHR operation, and (iii) an arbitrary list of additional arguments that are "passed through" the XHR object to the success callback function.

+ +

Line 1 declares a function invoked when the XHR operation completes successfully.  It, in turn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 7). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function.

+ +

Line 3 declares a function invoked when the XHR operation fails to complete successfully.

+ +

Line 7 stores on the XHR object the success callback function given as the second argument to loadFile.

+ +

Line 8 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable oReq, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess.

+ +

Line 9 designates the function xhrSuccess as the callback to be invoked when the onload event fires, that is, when the XHR sucessfully completes.  

+ +

Line 10 designates the function xhrError as the callback to be invoked when the XHR requests fails to complete.

+ +

Line 11 specifies true for its third parameter to indicate that the request should be handled asynchronously.

+ +

Line 12 actually initiates the request.

+ +

Example: using a timeout

+ +

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

+ +
function loadFile(sUrl, timeout, callback){
+
+    var args = arguments.slice(3);
+    var xhr = new XMLHttpRequest();
+    xhr.ontimeout = function () {
+        console.error("The request for " + url + " timed out.");
+    };
+    xhr.onload = function() {
+        if (xhr.readyState === 4) {
+            if (xhr.status === 200) {
+                callback.apply(xhr, args);
+            } else {
+                console.error(xhr.statusText);
+            }
+        }
+    };
+    xhr.open("GET", url, true);
+    xhr.timeout = timeout;
+    xhr.send(null);
+}
+ +

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

+ +

Usage:

+ +
function showMessage (sMsg) {
+  alert(sMsg + this.responseText);
+}
+
+loadFile("message.txt", 2000, showMessage, "New message!\n");
+
+ +

Here, we're specifying a timeout of 2000 ms.

+ +
+

Note: Support for timeout was added in {{Gecko("12.0")}}.

+
+ +

Synchronous request

+ +
Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
+ +

In rare cases, the use of a synchronous method is preferable to an asynchronous one.

+ +

Example: HTTP synchronous request

+ +

This example demonstrates how to make a simple synchronous request.

+ +
var request = new XMLHttpRequest();
+request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
+request.send(null);
+
+if (request.status === 200) {
+  console.log(request.responseText);
+}
+
+ +

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

+ +

Line 5 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

+ +

Example: Synchronous HTTP request from a Worker

+ +

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

+ +

example.html (the main page):

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+  var worker = new Worker("myTask.js");
+  worker.onmessage = function(event) {
+    alert("Worker said: " + event.data);
+  };
+
+  worker.postMessage("Hello");
+</script>
+</head>
+<body></body>
+</html>
+
+ +

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

+ +
Hello World!!
+
+ +

myTask.js (the Worker):

+ +
self.onmessage = function (event) {
+  if (event.data === "Hello") {
+    var xhr = new XMLHttpRequest();
+    xhr.open("GET", "myFile.txt", false);  // synchronous request
+    xhr.send(null);
+    self.postMessage(xhr.responseText);
+  }
+};
+
+ +
Note: The effect, because of the use of the Worker, is however asynchronous.
+ +

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

+ +

Adapting Sync XHR usecases to the Beacon API

+ +

There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events.  The navigator.sendBeacon API can support these usecases typically while delivering a good UX.

+ +

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    var client = new XMLHttpRequest();
+    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
+    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
+    client.send(analyticsData);
+}
+
+ +

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

+ +

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon() method.

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    navigator.sendBeacon("/log", analyticsData);
+}
+
+ +

See also

+ + + +

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

diff --git a/files/es/web/api/xmlhttprequest/timeout/index.html b/files/es/web/api/xmlhttprequest/timeout/index.html new file mode 100644 index 0000000000..a9fec94792 --- /dev/null +++ b/files/es/web/api/xmlhttprequest/timeout/index.html @@ -0,0 +1,67 @@ +--- +title: XMLHttpRequest.timeout +slug: Web/API/XMLHttpRequest/timeout +tags: + - AJAX + - Propiedad + - Referencia + - XHR + - XHR asincrónico + - XMLHttpRequest + - XMLHttpRequest asincrónico + - tiempo de espera + - timeout +translation_of: Web/API/XMLHttpRequest/timeout +--- +
{{APIRef('XMLHttpRequest')}}
+ +

La propiedad XMLHttpRequest.timeout es un unsigned long que representa el número de milisegundos que puede tomar una solicitud antes de que se finalice automáticamente. El valor por defecto es 0, lo que significa que no hay tiempo de espera (timeout). Timeout no debe utilizarse para solicitudes XMLHttpRequests sincrónicas usadas en un {{Glossary('document environment')}}, pues generará una excepción InvalidAccessError. Cuando ocurre un tiempo de espera, se dispara un evento timeout. {{gecko_minversion_inline("12.0")}}

+ +
+
+
Nota: No puede usar un timeout para solicitudes sincrónicas con una ventana propietaria (owning window).
+
+
Uso de timeout con una solicitud asincrónica
+
+ +

En Internet Explorer, la propiedad timeout se puede establecer solo después de llamar al método open() y antes de llamar al método send().

+ +

Ejemplo

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.timeout = 2000; // tiempo en milisegundos
+
+xhr.onload = function () {
+  // Solicitud finalizada. Haz el procesamiento aquí.
+};
+
+xhr.ontimeout = function (e) {
+  // Tiempo de espera del XMLHttpRequest agotado. Haz algo aquí.
+};
+
+xhr.send(null);
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('XMLHttpRequest', '#the-timeout-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("api.XMLHttpRequest.timeout")}}

diff --git a/files/es/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/es/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..c3d2b48e7f --- /dev/null +++ b/files/es/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,447 @@ +--- +title: Using XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +

{{APIRef("XMLHttpRequest")}}

+ +

En esta guía le echaremos un vistazo a cómo usar {{domxref("XMLHttpRequest")}} para enviar solicitudes HTTP con el objetivo de intercambiar datos entre el sitio web y el servidor. Se incluyen ejemplos, tanto para los casos de uso comunes de XMLHttpRequest, como para los más inusuales.

+ +

Para enviar una solicitud HTTP, cree un objeto XMLHttpRequest, abra una URL y envíe la solicitud. Una vez que la transacción haya sido completada, el objeto contendrá información útil tal como el cuerpo de la respuesta y el estado HTTP del resultado.

+ +
function reqListener () {
+  console.log(this.responseText);
+}
+
+var oReq = new XMLHttpRequest();
+oReq.addEventListener("load", reqListener);
+oReq.open("GET", "http://www.example.org/example.txt");
+oReq.send();
+ +

Solicitudes Síncronas y Asíncronas

+ +

XMLHttpRequest soporta tanto comunicaciones síncronas como asíncronas.

+ +
Nota: No deberias usar XMLHttpRequests síncronas porque, dada la naturaleza inherentemente asíncrona del intercambio de datos en las redes, hay multiples formas en que la memoria y eventos se puedan perder usando solicitudes síncronas.
+ +

En versiones de Firefox anteriores a Firefox 3, (solicitudes) XMLHttpRequest síncronas bloqueaban la interfaz de usuario.  Con tal de permitirle al usuario terminar solicitudes congeladas, Firefox 3 ya no lo hace.

+ +

Ejemplo: Solicitud síncrona

+ +

Este ejemplo demuestra como hacer una solicitud síncrona.

+ +
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', false);
+req.send(null);
+if (req.status == 200)
+  dump(req.responseText);
+ +

En la línea 1 se instancia un objeto XMLHttpRequest.  Después en la línea 2 se abre una nueva solicitud, especificando que una solicitud GET se utilizará para extraer la pagina de inicio de Mozilla.org, y que la operación no debe ser asíncrona.

+ +

En la línea 3 se envía la solicitud.  El parámetro null indica que la solicitud GET no necesita contenido en el cuerpo.

+ +

En la línea 4 se verifica el código de estatus después de que la transacción se completa.  Si el resultado es 200 -- El código HTTP para resultado "OK"-- el contenido de texto del documento se escribe en la consola.

+ +

Ejemplo: Solicitudes síncronas no-HTTP

+ +

A pesar de su nombre, XMLHttpRequest se puede usar para hacer solicitudes que no sean de HTTP.  Este ejemplo muestra como usarlo para extraer un archivo del sistemas de archivos local.

+ +
var req = new XMLHttpRequest();
+req.open('GET', 'file:///home/user/file.json', false);
+req.send(null);
+if(req.status == 0)
+  dump(req.responseText);
+ +

La clave aqui es notar que el estado del resultado se compara con 0 en lugar de 200.  Esto es porque los esquemas file y ftp no usan los codigos de resultado de HTTP.

+ +

Ejemplo: Solicitudes asíncronas

+ +

Si usas XMLHttpRequest desde una extensión, deberias usarla asíncronamente.  En este caso, recibiras una llamada de regreso cuando se hallan recibido los datos, lo cual permite al navegador continuar trabajando con normalidad mientras se maneja tu solicitud.

+ +
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', true);
+req.onreadystatechange = function (aEvt) {
+  if (req.readyState == 4) {
+     if(req.status == 200)
+      dump(req.responseText);
+     else
+      dump("Error loading page\n");
+  }
+};
+req.send(null); 
+ +

La linea 2 especifica true en su tercer parametro indicando que la solicitud debe manejarse asíncronamente.

+ +

Line 3 crea un objeto función para manejar eventos y lo asigna al atributo de la solicitud onreadystatechange.  Este manejador observa el readyState de la solicitud verificando si la transacción se ha completado en la linea 4, si así es, y el estatus HTTP es 200, imprime el contenido recibido.  Si ocurrió un error, se muestra un mensaje de error.

+ +

La linea 11 de hecho inicia la solicitud.  La función onreadystatechange es llamada siempre que el estado de una solicitud cambia.

+ +

Analizando y Manipulando el Texto de Respuesta HTML

+ +

Si usas XMLHttpRequest para obtener el contenido de una página HTML remota, el responseText (texto de la respuesta) sera una cadena que contenga una "sopa" de etiquetas HTML, lo que puede ser dificil de analizar y manipular. Existen tres maneras principales de analizar estas cadenas HTML

+ +
    +
  1. Analizar con nsIScriptableUnescapeHTML repidamente convertira la cadena HTML en DOM, al mismo tiempo que tira javascript y otros elementos avanzados, incluyendo la etiqueta <head> de la página.
  2. +
  3. RegExp se puede usar si de antemano conoces el HTML que vendra en el responseText. Quizas quieras remover los saltos de linea, si usas RegExp para escanear considerandolos. Sin embargo, este metodo es un "ultimo recurso" ya que si el HTML cambia ligeramente, posiblemente fallara.
  4. +
  5. Usar un hidden chrome o un content-level iframe para cargar toda la pagina también se puede hacer para manipularla luego como DOM, sin embargo existen riesgos de seguridad al dar a código remoto este nivel de acceso privilegiado, que puede causar problemas en la revisión de tu addon. Por ejemplo, si una pagina ejecuta el comando común "document.location = redirecttothispage.html" para cargar, esto se interpretara como cambiar la locación del navegador (document.location en una extensión) en contraposición a la locación de una página web (content.document.location en una extensión), y en consecuecia destruir todos los componentes del navegador. Alternativamente, y de algun modo mas seguro, una cadena responseText adquirida mediante XMLHttpRequest se puede analizar con RegExp para remover problemas de javascript, luego cargada en un iframe oculto previamente  establecido:
  6. +
+ +
document.getElementById('hiddenXULiframe').contentWindow.document.body.innerHTML = req.responseText
+
+ +

Using FormData objects

+ +

{{ gecko_minversion_header("2") }}

+ +

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It's primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".

+ +

Creating a FormData object from scratch

+ +

You can build a FormData object yourself, instantiating it then appending fields to it by calling its append() method, like this:

+ +
var formData = new FormData();
+
+formData.append("username", "Groucho");
+formData.append("accountnum", 123456);
+formData.append("afile", fileInputElement.files[0]);
+
+var xhr = new XMLHttpRequest();
+xhr.open("POST", "http://foo.com/submitform.php");
+xhr.send(formData);
+
+ +

This example builds a FormData object containing values for fields named "username" and "accountnum", then uses the XMLHttpRequest method send() to send the form's data.

+ +

Retrieving a FormData object from an HTML form

+ +

To construct a FormData object that contains the data from an existing {{ HTMLElement("form") }}, specify that form element when creating the FormData object:

+ +
newFormData = new FormData(someFormElement);
+
+ +

For example:

+ +
var formElement = document.getElementById("myFormElement");
+var xhr = new XMLHttpRequest();
+xhr.open("POST", "submitform.php");
+xhr.send(new FormData(formElement));
+
+ +

You can also add data to the FormData object between retrieving it from a form and sending it, like this:

+ +
var formElement = document.getElementById("myFormElement");
+formData = new FormData(formElement);
+formData.append("serialnumber", serialNumber++);
+xhr.send(formData);
+
+ +

This lets you augment the form's data before sending it along, to include additional information that's not necessarily user editable on the form.

+ +

Sending files using a FormData object

+ +

You can also send files using FormData. Simply include an {{ HTMLElement("input") }} element of type "file":

+ +
<form enctype="multipart/form-data" method="post" name="fileinfo" id="fileinfo">
+  <label>Your email address:</label>
+  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64"><br />
+  <label>Custom file ID:</label>
+  <input type="text" name="fileid" size="12" maxlength="32"><br />
+  <label>File to stash:</label>
+  <input type="file" name="file" required>
+</form>
+<div id="output"></div>
+<a href="javascript:sendForm()">Stash the file!</a>
+
+ +

Then you can send it using code like the following:

+ +
function sendForm() {
+  var output = document.getElementById("output");
+  var data = new FormData(document.getElementById("fileinfo"));
+
+  data.append("CustomField", "This is some extra data");
+
+  var xhr = new XMLHttpRequest();
+  xhr.open("POST", "stash.pl", false)
+  xhr.send(data);
+  if (xhr.status == 200) {
+    output.innerHTML += "Uploaded!<br />";
+  } else {
+    output.innerHTML += "Error " + xhr.status + " occurred uploading your file.<br />";
+  }
+}
+
+ +

Note that this example is directing the output to a Perl CGI script running on the server, and handles HTTP errors, although not prettily.

+ +

Handling binary data

+ +

Although XMLHttpRequest is most commonly used to send and receive textual data, it can be used to send and receive binary content.

+ +

Receiving binary data

+ +

The load_binary_resource() function shown below loads binary data from the specified URL, returning it to the caller.

+ +
function load_binary_resource(url) {
+  var req = new XMLHttpRequest();
+  req.open('GET', url, false);
+  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
+  req.overrideMimeType('text/plain; charset=x-user-defined');
+  req.send(null);
+  if (req.status != 200) return '';
+  return req.responseText;
+}
+
+ +

The magic happens in line 5, which overrides the MIME type, forcing Firefox to treat it as plain text, using a user-defined character set.  This tells Firefox not to parse it, and to let the bytes pass through unprocessed.

+ +
var filestream = load_binary_resource(url);
+var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)
+ +

The example above fetches the byte at offset x within the loaded binary data.  The valid range for x is from 0 to filestream.length-1.

+ +

See downloading binary streams with XMLHttpRequest for a detailed explanation. See also downloading files.

+ +

Receiving binary data using JavaScript typed arrays

+ +

{{ gecko_minversion_header("2.0") }}

+ +

Gecko 2.0 {{ geckoRelease("2.0") }} adds a Gecko-specific mozResponseArrayBuffer property to the XMLHttpRequest object, which contains a JavaScript typed array representing the raw binary contents of the response from the server. This lets you read the binary data without taking any special steps.

+ +
var xhr = new XMLHttpRequest();
+xhr.open("GET", "binary_file", false);
+xhr.send(null);
+
+buffer = xhr.mozResponseArrayBuffer;
+if (buffer) {
+  var byteArray = new UInt8Array(buffer);
+  for (var i=0; i<byteArray.byteLength; i++) {
+    // do something with each byte in the array
+  }
+}
+
+ +

This example reads a binary file and interprets it as 8-bit unsigned integers.

+ +

Sending binary data

+ +

This example transmits binary content asynchronously, using the POST method.

+ +
var req = new XMLHttpRequest();
+req.open("POST", url, true);
+// set headers and mime-type appropriately
+req.setRequestHeader("Content-Length", 741);
+req.sendAsBinary(aBody);
+ +

Line 4 sets the Content-Length header to 741, indicating that the data is 741 bytes long.  Obviously you need to change this value based on the actual size of the data being sent.

+ +

Line 5 uses the sendAsBinary() method to initiate the request.

+ +

You can also send binary content by passing an instance of the {{ interface("nsIFileInputStream") }} to send().  In that case, you don't have to set the Content-Length header yourself, as the information is fetched from the stream automatically:

+ +
// Make a stream from a file.
+var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
+                       .createInstance(Components.interfaces.nsIFileInputStream);
+stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance
+
+// Try to determine the MIME type of the file
+var mimeType = "text/plain";
+try {
+  var mimeService = Components.classes["@mozilla.org/mime;1"]
+          .getService(Components.interfaces.nsIMIMEService);
+  mimeType = mimeService.getTypeFromFile(file); // file is an nsIFile instance
+}
+catch(e) { /* eat it; just use text/plain */ }
+
+// Send
+var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
+req.open('PUT', url, false); /* synchronous! */
+req.setRequestHeader('Content-Type', mimeType);
+req.send(stream);
+
+ +

Monitoring progress

+ +

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.

+ +

In Firefox 3.5 and later

+ +

Firefox 3.5 adds support for DOM progress event monitoring of XMLHttpRequest transfers; this follows the Web API specification for progress events.

+ +
var req = new XMLHttpRequest();
+
+req.addEventListener("progress", updateProgress, false);
+req.addEventListener("load", transferComplete, false);
+req.addEventListener("error", transferFailed, false);
+req.addEventListener("abort", transferCanceled, false);
+
+req.open();
+
+...
+
+// progress on transfers from the server to the client (downloads)
+function updateProgress(evt) {
+  if (evt.lengthComputable) {
+    var percentComplete = evt.loaded / evt.total;
+    ...
+  } else {
+    // Unable to compute progress information since the total size is unknown
+  }
+}
+
+function transferComplete(evt) {
+  alert("The transfer is complete.");
+}
+
+function transferFailed(evt) {
+  alert("An error occurred while transferring the file.");
+}
+
+function transferCanceled(evt) {
+  alert("The transfer has been canceled by the user.");
+}
+
+ +

Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest.  See {{ interface("nsIDOMProgressEvent") }} and {{ interface("nsIXMLHttpRequestEventTarget") }} for details on these events.

+ +
Note: You need to add the event listeners before calling open() on the request.  Otherwise the progress events will not fire.
+ +

The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields.  However, if the lengthComputable field is false, the total length is not known and will be zero.

+ +

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

+ +
var req = new XMLHttpRequest();
+
+req.upload.addEventListener("progress", updateProgress, false);
+req.upload.addEventListener("load", transferComplete, false);
+req.upload.addEventListener("error", transferFailed, false);
+req.upload.addEventListener("abort", transferCanceled, false);
+
+req.open();
+ +
Note: Progress events are not available for the file: protocol.
+ +

In Firefox 3 and earlier

+ +

If, for example, you wish to provide progress information to the user while the document is being received, you can use code like this:

+ +
function onProgress(e) {
+  var percentComplete = (e.position / e.totalSize)*100;
+  // ...
+}
+
+function onError(e) {
+  alert("Error " + e.target.status + " occurred while receiving the document.");
+}
+
+function onLoad(e) {
+  // ...
+}
+// ...
+var req = new XMLHttpRequest();
+req.onprogress = onProgress; // or req.addEventListener("progress", onProgress, false);
+req.open("GET", url, true);
+req.onload = onLoad; // or req.addEventListener("load", onLoad, false);
+req.onerror = onError; // or req.addEventListener("error", onError, false);
+req.send(null);
+
+ +

The onprogress event's attributes, position and totalSize, indicate the current number of bytes received and the total number of bytes expected, respectively.

+ +

All of these events have their target attribute set to the XMLHttpRequest they correspond to.

+ +
Note: Firefox 3 properly ensures that the values of the target, currentTarget, and this fields of the event object are set to reference the correct objects when calling event handlers for XML documents represented by XMLDocument. See {{ Bug(198595) }} for details.
+ +

Cross-site XMLHttpRequest

+ +
+

Este artículo cubre características introducidas en Firefox 3.5.

+
+ +

Firefox 3.5 supports cross-site requests by implementing the web applications working group's Access Control for Cross-Site Requests standard.  As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work.  Otherwise, an INVALID_ACCESS_ERR exception is thrown.

+ +

Bypassing the cache

+ +

Normally, XMLHttpRequest tries to retrieve content from the cache, if it's available.  To bypass this, do the following:

+ +
var req = new XMLHttpRequest();
+req.open('GET', url, false);
+req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
+req.send(null);
+ +
Note: This approach will only work in Gecko-based software, as the channel attribute is Gecko-specific.
+ +

An alternate, cross-browser compatible approach is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate.  For example:

+ +
http://foo.com/bar.html
+ +

becomes

+ +
http://foo.com/bar.html?12345
+ +

and

+ +
http://foo.com/bar.html?foobar=baz
+ +

becomes

+ +
http://foo.com/bar.html?foobar=baz&12345
+ +

Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

+ +

You can automatically adjust URLs using the following code:

+ +
var req = new XMLHttpRequest();
+req.open("GET", url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(), false);
+req.send(null); 
+ +

Security

+ +

{{ fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy..XMLHttpRequest.open to allAccess to give specific sites cross-site access.  This is no longer supported.") }}

+ +

Downloading JSON and JavaScript from extensions

+ +

For security reasons, extensions should never use eval() to parse JSON or JavaScript code downloaded from the web.  See Downloading JSON and JavaScript in extensions for details.

+ +

Using XMLHttpRequest from JavaScript modules / XPCOM components

+ +

Instantiating XMLHttpRequest from a JavaScript module or an XPCOM component works a little differently; it can't be instantiated using the XMLHttpRequest() constructor. The constructor is not defined inside components and the code results in an error. You'll need to create and use it using a different syntax.

+ +

Instead of this:

+ +
var req = new XMLHttpRequest();
+req.onprogress = onProgress;
+req.onload = onLoad;
+req.onerror = onError;
+req.open("GET", url, true);
+req.send(null);
+
+ +

Do this:

+ +
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
+req.onprogress = onProgress;
+req.onload = onLoad;
+req.onerror = onError;
+req.open("GET", url, true);
+req.send(null);
+
+ +

For C++ code you would need to QueryInterface the component to an nsIEventTarget in order to add event listeners, but chances are in C++ using a channel directly would be better.

+ +

See also

+ +
    +
  1. MDC AJAX introduction
  2. +
  3. HTTP access control
  4. +
  5. How to check the security state of an XMLHTTPRequest over SSL
  6. +
  7. XMLHttpRequest - REST and the Rich User Experience
  8. +
  9. Microsoft documentation
  10. +
  11. Apple developers' reference
  12. +
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. +
  15. The XMLHttpRequest Object: W3C Working Draft
  16. +
  17. Web Progress Events specification
  18. +
  19. Reading Ogg files with JavaScript (Chris Double)
  20. +
-- cgit v1.2.3-54-g00ecf