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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
|
---
title: 入門篇
slug: Web/Guide/AJAX/Getting_Started
tags:
- AJAX
- API
- Advanced
- JavaScript
- WebMechanics
- XMLHttpRequest
translation_of: Web/Guide/AJAX/Getting_Started
---
<p class="summary">這篇文章說明 AJAX 相關技術的基礎,並提供兩個簡單的實際操作範例供您入門。</p>
<h3 id="AJAX_是什麼?">AJAX 是什麼?</h3>
<p>AJAX 代表 <strong>A</strong>synchronous <strong>J</strong>avaScript <strong>A</strong>nd <strong>X</strong>ML,即非同步 JavaScript 及 XML。簡單地說,AJAX 使用 {{domxref("XMLHttpRequest")}} 物件來與伺服器進行通訊。它可以傳送並接收多種格式的資訊,包括 JSON、XML、HTML、以及文字檔案。AJAX 最吸引人的特點是「非同步」的本質,這代表它可以與伺服溝通、交換資料、以及更新頁面,且無須重整網頁。</p>
<p>有兩項即將討論到的特點如下︰</p>
<ul>
<li>無須重新載入整個頁面,便能對伺服器發送請求</li>
<li>分析並運用 XML 文件</li>
</ul>
<h3 id="第一步_–_如何發出_HTTP_請求">第一步 – 如何發出 HTTP 請求</h3>
<p>為了使用 JavaScript 向伺服器發送 HTTP 請求,便需要一個能夠提供相關功能的類別實體(an instance of a class)。這樣的類別最初由 Internet Explorer 以 ActiveX 物件的方式引入,稱為 <code>XMLHTTP</code>。Mozilla、Safari 及其他瀏覽器則隨後跟進,實作了 <code>XMLHttpRequest</code> 類別,以提供微軟最初的 ActiveX 物件中的方法及屬性。</p>
<p>因此,為了建立能夠跨瀏覽器的物件實體,可以這麼寫:</p>
<pre class="brush: js notranslate">// Old compatibility code, no longer needed.
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
</pre>
<div class="note"><strong>備註:</strong>出於解說上的需要,上述代碼使用最簡方式建立 XMLHTTP 的實體。較貼近實際運用的範例,見第三步。</div>
<p>部分版本的 Mozilla 瀏覽器,在伺服器送回的資料未含 XML <code>mime-type</code> 標頭(header)時會出錯。為了避免這個問題,你可以用下列方法覆寫伺服器傳回的檔頭,以免傳回的不是 <code>text/xml</code>。</p>
<pre class="notranslate">httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');
</pre>
<p>接下來是要決定伺服器傳回資料後的處理方式,此時你只要以 <code>onreadystatechange</code> 這個屬性指明要處理傳回值的 JavaScript 函式名稱即可,例如:</p>
<pre class="brush: js notranslate"><code>httpRequest.onreadystatechange = nameOfTheFunction;</code></pre>
<p>注意,指定的函式名稱後不加括號也沒有參數。這只是簡單的賦值,而非真的呼叫函數。除了指定函式名稱外,你也能用 Javascript 即時定義函式的技巧(稱為〝匿名函數〞)來定一個新的處理函式,如下:</p>
<pre class="brush: js notranslate">httpRequest.onreadystatechange = function(){
// 做些事
};
</pre>
<p>決定處理方式之後你得確實發出 request,此時需叫用 HTTP request 類別的 <code>open()</code> 及 <code>send()</code> 方法,如下:</p>
<pre class="brush: js notranslate">httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send();
</pre>
<ul>
<li><code>open()</code> 的第一個參數是 HTTP request 的方法,也就是從 GET、POST、HEAD 等伺服器支援的方法中擇一使用。為遵循 HTTP 標準,請記得這些方法都是大寫,否則有的瀏覽器(如 Firefox)不會處理這些請求。其他可用的 HTTP request 方法的列表請參考 <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">W3C 規格書</a>。</li>
<li>第二個參數是請求頁面的 URL。基於安全考量,你不能叫用同網域以外的網頁。如果網域不同,則叫用 <code>open()</code> 時會出現「權限不足,拒絕存取」那類的錯誤。常見的錯誤多為在 domain.tld 的網站下呼叫 www.domain.tld 中的網頁,僅是一點點差別都不行。</li>
<li>第三個參數決定此 request 是否不同步進行,如果設定為 <code>TRUE</code> 則即使伺服器尚未傳回資料也會繼續執行其餘的程式,這也就是 AJAX 中第一個 A 代表的意義。</li>
</ul>
<p><code>send()</code> 的參數在以 POST 發出 request 時,可以是任何想傳給伺服器的東西,而資料則以查詢字串的方式列出,例如:</p>
<pre class="notranslate"><code>"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"</code></pre>
<p>不過如果你想要以 POST 方式傳送資料,則必須先將 MIME 型態改好,如下:</p>
<pre class="brush: js notranslate">httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
</pre>
<p>否則伺服器就不會理你傳過來的資料了。</p>
<h3 id="第二步_–_處理伺服器傳回的資料">第二步 – 處理伺服器傳回的資料</h3>
<p>傳出 request 時必須提供處理傳回值的函數名稱,這個函數是用來處理伺服器的回應。</p>
<pre class="brush: js notranslate">httpRequest.onreadystatechange = nameOfTheFunction;
</pre>
<p>那麼來看看這個函數該做些什麼。首先,它必須檢查 request 目前的狀態。如果狀態值為 4 代表伺服器已經傳回所有資訊了,便可以開始解析所得資訊。</p>
<pre class="brush: js notranslate">if (httpRequest.readyState === XMLHttpRequest.DONE) {
// 一切 ok, 繼續解析
} else {
// 還沒完成
}
</pre>
<p><code>readyState</code> 所有可能的值如下:</p>
<ul>
<li>0(還沒開始)</li>
<li>1(讀取中)</li>
<li>2(已讀取)</li>
<li>3(資訊交換中)</li>
<li>4(一切完成)</li>
</ul>
<p>(<a class="external" href="http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/readystate_1.asp">資料來源:MSDN</a>)</p>
<p>接下來要檢查伺服器傳回的 HTTP 狀態碼。所有狀態碼列表可於 <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">W3C 網站</a>上查到,但我們要管的是 <code>200 OK</code> 這種狀態。</p>
<pre class="brush: js notranslate">if (httpRequest.status === 200) {
// 萬事具備
} else {
// 似乎有點問題。
// 或許伺服器傳回了 404(查無此頁)
// 或者 500(內部錯誤)什麼的。
}
</pre>
<p>檢查傳回的 HTTP 狀態碼後,要怎麼處理傳回的資料就由你決定了。有兩種存取資料的方式:</p>
<ul>
<li><code>httpRequest.responseText</code> – 這樣會把傳回值視為字串用</li>
<li><code>httpRequest.responseXML</code> – 這樣會把傳回值視為 <code>XMLDocument</code> 物件,而後可用 JavaScript DOM 相關函式處理</li>
</ul>
<h3 id="第三步_–_簡單範例">第三步 – 簡單範例</h3>
<p>好,接著就做一次簡單的 HTTP 範例,演示方才的各項技巧。這段 JavaScript 會向伺服器要一份裡頭有「I'm a test.」字樣的 HTML 文件(<code>test.html</code>),而後以 <code>alert()</code> 將文件內容列出。</p>
<pre class="brush: html notranslate"><button id="ajaxButton" type="button">Make a request</button>
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test.html');
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
</pre>
<p>在此範例中:</p>
<ul>
<li>首先使用者按下「Make a request」</li>
<li>這麼一來就會呼叫 <code>makeRequest()</code> 函式,亦傳入參數值 <code>test.html</code> (也就是那份 HTML 檔的名稱,放在同目錄下)</li>
<li>接著發出 request,而後會將主導權交給 <code>onreadystatechange</code> 指定的 <code>alertContents()</code> 函式</li>
<li><code>alertContents()</code> 檢查回應是否正常,而後以 <code>alert()</code> 將 <code>test.html</code> 的內容列出</li>
</ul>
<p>你可以<a class="external" href="http://www.w3clubs.com/mozdev/httprequest_test.html">由此測試本例</a>,也可以參考<a class="external" href="http://www.w3clubs.com/mozdev/test.html">測試檔案</a>。</p>
<div class="note">Note:如果你傳送一個要求到一段代碼,而這段代碼將回應XML而非靜態的HTML檔,那則必須要設定一個可以在IE中運作的header。如果我們不設定header <code>Content-Type: application/xml</code>,IE將會在我們試圖運作的XML項目行下,回應一個"Object Expected" 的錯誤。</div>
<div class="note">Note 2: 如果我們沒有設定header <code>Cache-Control: no-cache</code>,那瀏覽器將會藏匿response並且不再重新傳送request,造成除錯上的挑戰。我們也可以增加一個 always-different GET 參數,像是 timestamp 或 random number (詳見<a href="https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache">bypassing the cache</a>)</div>
<div class="note"><strong>Note 3</strong>: If the <code>httpRequest</code> variable is used globally, competing functions calling <code>makeRequest()</code> can overwrite each other, causing a race condition. Declaring the <code>httpRequest </code>variable local to a <a href="/en/JavaScript/Guide/Closures">closure</a> containing the AJAX functions avoids this.</div>
<p>In the event of a communication error (such as the server going down), an exception will be thrown in the <code>onreadystatechange</code> method when accessing the response status. To mitigate this problem, you could wrap your <code>if...then</code> statement in a <code>try...catch</code>:</p>
<pre class="brush: js notranslate">function alertContents() {
try {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
catch( e ) {
alert('Caught Exception: ' + e.description);
}
}
</pre>
<h3 id="第四步_–_運用_XML_資料">第四步 – 運用 XML 資料</h3>
<p>前面的例子中,在收到 HTTP 傳回值後我們以物件的 <code>reponseText</code> 屬性接收 <code>test.html</code> 檔案的內容,接著來試試 <code>responseXML</code> 屬性。</p>
<p>首先,我們得做個格式正確的 XML 文件以便稍後取用。文件 (<code>test.xml</code>) 內容如下:</p>
<pre class="brush: html notranslate"><?xml version="1.0" ?>
<root>
I'm a test.
</root>
</pre>
<p>在程式中,我們叫用檔案的地方只須略事修改如下:</p>
<pre class="brush: html notranslate">...
onclick="makeRequest('test.xml')">
...
</pre>
<p>接著在 <code>alertContents()</code> 中,我們把 <code>alert(http_request.responseText);</code> 改成這樣:</p>
<pre class="brush: js notranslate">var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);
</pre>
<p>這樣一來我們便可取得 <code>responseXML</code> 所傳回的 <code>XMLDocument</code> 物件,而後以 DOM 方法取用 XML 文件的內容。你可以參考 <a class="external" href="http://www.w3clubs.com/mozdev/test.xml"><code>test.xml</code> 的原始碼</a> 以及修改過後的<a class="external" href="http://www.w3clubs.com/mozdev/httprequest_test_xml.html">測試程式</a>。</p>
<p>關於 DOM 方法,請參考 <a class="external" href="http://www.mozilla.org/docs/dom/">Mozilla DOM</a> 文件。</p>
<h3 id="Step_5_–_Working_with_data">Step 5 – Working with data</h3>
<p>Finally, let's send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, <code>test.php</code>, which will take the data we send and return a "computed" string - "Hello, [user data]!" - which we'll <code>alert().</code></p>
<p>First we'll add a text box to our HTML so the user can enter their name:</p>
<pre class="brush: html notranslate"><label>Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span></pre>
<p>We'll also add a line to our event handler to get the user's data from the text box and send it to the <code>makeRequest()</code> function along with the URL of our server-side script:</p>
<pre class="brush: js notranslate"> document.getElementById("ajaxButton").onclick = function() {
var userName = document.getElementById("ajaxTextbox").value;
makeRequest('test.php',userName);
};
</pre>
<p>We need to modify <code>makeRequest()</code> to accept the user data and pass it along to the server. We'll change the request method from <code>GET</code> to <code>POST</code>, and include our data as a parameter in the call to <code>httpRequest.send()</code>:</p>
<pre class="brush: js notranslate"> function makeRequest(url, userName) {
...
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('userName=' + encodeURIComponent(userName));
}
</pre>
<p>The function <code>alertContents()</code> can be written the same way it was in Step 3 to alert our computed string, if that's all the server returns. However, let's say the server is going to return both the computed string and the original user data. So if our user typed "Jane" in the text box, the server's response would look like this:</p>
<p><code>{"userData":"Jane","computedString":"Hi, Jane!"}</code></p>
<p>To use this data within <code>alertContents()</code>, we can't just alert the <code>responseText</code>, we have to parse it and alert <code>computedString</code>, the property we want:</p>
<pre class="brush: js notranslate">function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
alert(response.computedString);
} else {
alert('There was a problem with the request.');
}
}
}</pre>
<p>The <code>test.php file should contain the following:</code></p>
<pre class="brush: php notranslate"><code>$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['userName' => $name, 'computedString' => $computedString];
echo json_encode($array);</code></pre>
<p><code>For more on DOM methods, be sure to check <a class="external" href="http://www.mozilla.org/docs/dom/">Mozilla's DOM implementation</a> documents.</code></p>
|