aboutsummaryrefslogtreecommitdiff
path: root/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html
blob: 28675abd794ba4279578ff48cd2e9fd5af0cd3cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
---
<p><code>XMLHttpRequest</code> soporta solicitudes síncronas y asíncronas, pero la mas preferida es la asíncrona por razones de rendimiento</p>

<p><span id="result_box" lang="es"><span>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</span></span></p>

<h2 id="Peticiones_asíncronas">Peticiones asíncronas</h2>

<p><span id="result_box" lang="es"><span>Si se utiliza <code>XMLHttpRequest</code> de forma asíncrona, recibirá una devolución de llamada cuando los datos se hayan recibido .</span> <span>Esto permite que el navegador continúe funcionando de forma normal mientras se procesa la solicitud.</span></span></p>

<h3 id="Ejemplo_Enviar_un_archivo_a_la_consola"><span id="result_box" lang="es"><span>Ejemplo: Enviar un archivo a la consola</span></span></h3>

<p><span class="short_text" id="result_box" lang="es"><span>Este es el uso más simple de la asíncronia </span></span><code>XMLHttpRequest</code>.</p>

<pre class="brush: js">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); </pre>

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

<p>Line 3 creates an event handler function object and assigns it to the request's <code>onload</code> attribute.  This handler looks at the request's <code>readyState</code> 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.</p>

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

<h3 id="Ejemplo_Creando_una_funcion_estandar_para_leer_archivos_externos.">Ejemplo: Creando una funcion estandar para leer archivos externos.</h3>

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

<pre class="brush: js">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);
}
</pre>

<p>Usage:</p>

<pre class="brush: js">function showMessage (sMsg) {
  alert(sMsg + this.responseText);
}

loadFile("message.txt", showMessage, "New message!\n\n");
</pre>

<p>The signature of the utility function <em><strong>loadFile</strong></em> 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.</p>

<p>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.</p>

<p>Line 3 declares a function invoked when the XHR operation fails to complete successfully.</p>

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

<p>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.</p>

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

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

<p>Line 11 specifies <code>true</code> for its third parameter to indicate that the request should be handled asynchronously.</p>

<p>Line 12 actually initiates the request.</p>

<h3 id="Example_using_a_timeout">Example: using a timeout</h3>

<p>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 <code>timeout</code> property on the <code>XMLHttpRequest</code> object, as shown in the code below:</p>

<pre class="brush: js">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);
}</pre>

<p>Notice the addition of code to handle the "timeout" event by setting the <code>ontimeout</code> handler.</p>

<p>Usage:</p>

<pre class="brush: js">function showMessage (sMsg) {
  alert(sMsg + this.responseText);
}

loadFile("message.txt", 2000, showMessage, "New message!\n");
</pre>

<p>Here, we're specifying a timeout of 2000 ms.</p>

<div class="note">
<p><strong>Note:</strong> Support for <code>timeout</code> was added in {{Gecko("12.0")}}.</p>
</div>

<h2 id="Synchronous_request">Synchronous request</h2>

<div class="note"><strong>Note:</strong> 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.</div>

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

<h3 id="Example_HTTP_synchronous_request">Example: HTTP synchronous request</h3>

<p>This example demonstrates how to make a simple synchronous request.</p>

<pre class="brush: js">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);
}
</pre>

<p>Line 3 sends the request.  The <code>null</code> parameter indicates that no body content is needed for the <code>GET</code> request.</p>

<p>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.</p>

<h3 id="Example_Synchronous_HTTP_request_from_a_Worker">Example: Synchronous HTTP request from a <code>Worker</code></h3>

<p>One of the few cases in which a synchronous request does not usually block execution is the use of <code>XMLHttpRequest</code> within a <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>.</p>

<p><code><strong>example.html</strong></code> (the main page):</p>

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

  worker.postMessage("Hello");
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;&lt;/body&gt;
&lt;/html&gt;
</pre>

<p><code><strong>myFile.txt</strong></code> (the target of the synchronous <code><a href="/en/DOM/XMLHttpRequest" title="/en/XMLHttpRequest">XMLHttpRequest</a></code> invocation):</p>

<pre>Hello World!!
</pre>

<p><code><strong>myTask.js</strong></code> (the <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>):</p>

<pre class="brush: js">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);
  }
};
</pre>

<div class="note"><strong>Note:</strong> The effect, because of the use of the <code>Worker</code>, is however asynchronous.</div>

<p>It could be useful in order to interact in background with the server or to preload some content. See <a class="internal" href="/En/DOM/Using_web_workers" title="en/Using DOM workers">Using web workers</a> for examples and details.</p>

<h3 id="Adapting_Sync_XHR_usecases_to_the_Beacon_API">Adapting Sync XHR usecases to the Beacon API</h3>

<p>There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the <a class="internal" href="/en/DOM/window.onunload" title="en/DOM/window.onunload"><code>window.onunload</code></a> and <a class="internal" href="/en/DOM/window.onbeforeunload" title="en/DOM/window.onbeforeunload"><code>window.onbeforeunload</code></a> events.  The <a href="/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> API can support these usecases typically while delivering a good UX.</p>

<p><span>The following example (from the <a href="/en-US/docs/Web/API/Navigator/sendBeacon">sendBeacon docs</a>) 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.</span></p>

<pre class="brush: js">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);
}
</pre>

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

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

<pre class="brush: js">window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}
</pre>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest" title="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a></li>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest" title="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li>
 <li><a href="/en-US/docs/AJAX" title="/en-US/docs/AJAX">AJAX</a></li>
 <li><code><a href="/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a></code></li>
</ul>

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