aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html
blob: e8a148b5a9ae1c95b40e0763445ab0bbdf6503f6 (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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
---
title: Synchronous and asynchronous requests
slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
---
<p><code>XMLHttpRequest 支持同步和非同步請求,一般來說,建議使用非同步請求。</code></p>

<p>In short, synchronous requests block the execution of code which creates "freezing" on the screen and an unresponsive user experience. </p>

<h2 id="非同步請求">非同步請求</h2>

<p>If you use <code>XMLHttpRequest</code> from an extension, you should use it asynchronously.  In this case, you receive a callback when the data has been received, which lets the browser continue to work as normal while your request is being handled.</p>

<h3 id="範例_send_a_file_to_the_console_log">範例: send a file to the console log</h3>

<p>這是使用非同步<span style="font-family: consolas,monaco,andale mono,monospace;">XMLHttpRequest的基本方式</span></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>Line 2第3個參數為布林值,true表示非同步請求。</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="Example_creating_a_standard_function_to_read_external_files">Example: creating a standard function to read external files</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>Line 1 declares a function which will pass all arguments after the third to the <font face="Courier New, Andale Mono, monospace"><span style="line-height: normal;">callback </span></font>function when the file has been loaded.</p>

<p>Line 4 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 5, and if it is, and the HTTP status is 200, calls the callback function.  If an error occurred, an error message is displayed.</p>

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

<p>Line 14 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">  var args = arguments.slice(2);
  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="Irreplaceability_of_the_synchronous_use">Irreplaceability of the synchronous use</h3>

<p>There are some few cases in which the synchronous usage of XMLHttpRequest is not replaceable. This happens for example 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 (<a class="internal" href="#XMLHttpRequests_being_stopped" title="en/XMLHttpRequest/Using_XMLHttpRequest#XMLHttpRequests_being_stopped">see also below</a>).</p>

<p>Sending the usual XMLHttpRequest when the page unloaded poses a problem with the asynchronous response from the server: by the time the response comes back, the page has unloaded and the callback function won’t exist anymore. This generates a JavaScript “function is not defined” error.</p>

<p style="text-align: center;"><img alt="" class="internal" src="/@api/deki/files/6227/=AsyncUnload.jpg" style="height: 359px; width: 467px;"></p>

<p>A possible solution is to make sure that any AJAX requests that you make on unload are make synchronously instead of asynchronously. This will ensure that the page doesn’t finish unloading before the server response comes back.</p>

<h4 id="Example_1_Automatic_logout_before_exit">Example #1: Automatic logout before exit</h4>

<pre class="brush: js">window.onbeforeunload = function () {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "logout.php?nick=" + escape(myName), false);  // synchronous request
  xhr.send(null);
  if (xhr.responseText.trim() !== "logout done"); {  // "logout done" is the expected response text
    return "Logout has failed. Do you want to complete it manually?";
  }
};
</pre>

<h4 id="Example_2_Noting_if_a_user_abandon_the_site_without_clicking_any_link_and_registering_the_boring_page">Example #2: Noting if a user abandon the site without clicking any link and registering the boring page</h4>

<pre class="brush: js">&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;
(function () {

  function dontPanic () {
    bForsake = false;
    return true;
  }

  onload = function () {
    for (
      var aLinks = document.links, nLen = aLinks.length, nIdx = 0;
      nIdx &lt; nLen;
      aLinks[nIdx++].onclick = dontPanic
    );
  };

  onbeforeunload = function () {
    if (bForsake) {
      /* silent synchronous request */
      var oReq = new XMLHttpRequest();
      oReq.open("GET", "exit.php?leave=" + escape(location.href), false);
      oReq.send(null);
    }
  };

  var bForsake = true;

})();
&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/"&gt;Example link&lt;/a&gt;&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;</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>
</ul>

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