舊文件

此處文件僅供參考,請自行考量時效性與適用程度,其他庫藏文件請參考文件頁面
我們亟需您的協助,進行共筆系統搬移、及文件整理工作,詳情請查閱參與我們

「AJAX 上手篇」修訂間的差異

出自 MozTW Wiki

(回降至Shyangs最後一次編輯)
 
(未顯示由 36 位使用者於中間所作的 99 次修訂)
行 1: 行 1:
<!--<breadcrumbs></breadcrumbs>-->
+
{{MDC|AJAX:上手篇}}
 +
這篇文章說明 AJAX 相關技術的基礎,並提供實例供您上手。
  
編譯中: --[[用戶:BobChao|BobChao]] 19:48 2005年九月21日 (CST)
 
  
這篇文章說明 AJAX 相關技術的基礎,並提供實例供您上手。本文編譯自 [http://developer.mozilla.org/en/docs/AJAX:Getting_Started AJAX:Getting Started],在 devmo 有中文版之後可能會移過去。
+
== 第一步 – 說聲「請」 (又稱為「'''怎麼發出 XMLHttpRequest'''」) ==
  
== AJAX 是啥? ==
+
為了用 JavaScript 對伺服器發送 HTTP 要求,必須先以相關的類別(class)製出實體(instance)。Internet Explorer 首先以 ActiveX 物件方式提供 <code>XMLHTTP</code> 類別,而 Mozilla、Safari 及其他瀏覽器則隨後以 <code>XMLHttpRequest</code> 類別支援此 ActiveX 物件中的類別及屬性。
 
 
AJAX (Asynchronous JavaScript and XML, 非同步 JavaScript 及 XML 技術) 是個新詞,但內涵是兩個存在已有一段時間的 JavaScript 功能。這兩種功能以往一直被忽略,在 Gmail、Google suggest 及 Google Maps 出現後才一舉成名天下知。
 
 
 
這兩個 JavaScript 功能是:
 
* 在不重新讀取頁面的情況下對伺服器送出要求(request)
 
* 解析、使用 XML 文件
 
 
 
== 第一步 – 說聲「請」 (又稱為「怎麼發出 XMLHttpRequest」) ==
 
 
 
為了用 JavaScript 對伺服器發送 HTTP 要求,你必須先以相關的類別(class)製出實體(instance)。Internet Explorer 首先以 ActiveX 物件方式提供 <code>XMLHTTP</code> 類別,而 Mozilla、Safari 及其他瀏覽器則隨後以 <code>XMLHttpRequest</code> 類別支援此 ActiveX 物件中的類別及屬性。
 
  
 
因此,如果想跨瀏覽器,那麼可以這麼寫:
 
因此,如果想跨瀏覽器,那麼可以這麼寫:
行 40: 行 30:
 
<code>http_request.onreadystatechange = nameOfTheFunction;</code>
 
<code>http_request.onreadystatechange = nameOfTheFunction;</code>
  
Note that there are no brackets after the function name and no parameters passed. Also, instead of giving a function name, you can use the Javascript technique of defining functions on the fly and define the actions that will process the response right away, like this:
+
注意,指定的函式名稱後不加括號也沒有參數。除了指定函式名稱外,你也能用 Javascript 即時定義函式的方法來定一個新的處理函式,如下:
  
 
<pre>
 
<pre>
行 48: 行 38:
 
</pre>
 
</pre>
  
Next, after you've declared what will happen as soon as you receive the response, you need to actually make the request. You need to call the <code>open()</code> and <code>send()</code> methods of the HTTP request class, like this:
+
決定處理方式之後你得確實發出 request,此時需叫用 HTTP request 類別的 <code>open()</code> <code>send()</code> 方法,如下:
  
 
<pre>
 
<pre>
行 55: 行 45:
 
</pre>
 
</pre>
  
* The first parameter of the call to <code>open()</code> is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html W3C specs]  
+
* <code>open()</code> 的第一個參數是 HTTP request 的方法,也就是從 GET、POST、HEAD 中擇一使用,亦可用你主機上支援的方式。為遵循 HTTP 標準,請記得這些方法都是大寫,不然有的瀏覽器(如 Firefox)或許不會理你。其他 HTTP request 可以支援的方法列表請參考 [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html W3C 規格書]
* The second parameter is the URL of the page you're requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a 'permission denied' error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld.
+
* 第二個參數是目標 URL。基於安全考量,你不能叫用同網域以外的網頁。如果網域不同,則叫用 <code>open()</code> 時會出現「權限不足,拒絕存取」那類的錯誤。通常大夥會犯的錯誤多為在 domain.tld 網的網站下呼叫 www.domain.tld 中的網頁,僅是一點點差別都不行。
* The third parameter sets whether the request is asynchronous. If <code>TRUE</code>, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.
+
* 第三個參數決定此 request 是否不同步進行,如果設定為 <code>TRUE</code> 則即使伺服器尚未傳回資料也會繼續執行其餘的程式,這也就是 AJAX 中第一個 A 代表的意義。
  
The parameter to the <code>send()</code> method can be any data you want to send to the server if POST-ing the request. The data should be in the form of a query string, like:
+
<code>send()</code> 的參數在以 POST 發出 request 時可以是任何想傳給伺服器的東西,而資料則以查詢字串的方式列出,例如:
  
 
<code>name=value&anothername=othervalue&so=on</code>
 
<code>name=value&anothername=othervalue&so=on</code>
 +
 +
不過如果你想要以 POST 方式傳送資料,則必須先將 MIME 型態改好,如下:
 +
<pre>
 +
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 +
</pre>
 +
否則伺服器就不會理你傳過來的資料了。
  
 
== 第二步 – 「就上咩!」(又稱為「處理伺服器傳回的資料」) ==
 
== 第二步 – 「就上咩!」(又稱為「處理伺服器傳回的資料」) ==
  
Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.
+
傳出 request 時必須提供處理傳回值的函式名稱。
  
 
<code>http_request.onreadystatechange = nameOfTheFunction;</code>
 
<code>http_request.onreadystatechange = nameOfTheFunction;</code>
  
Let's see what this function should do. First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response is received and it's OK for you to continue processing it.
+
那麼來看看這個函式該做些什麼。首先,它必須檢查 request 目前的狀態:如果狀態值為 4 代表伺服器已經傳回所有資訊了,便可以開始解析所得資訊。
 
      
 
      
 
<pre>
 
<pre>
 
if (http_request.readyState == 4) {
 
if (http_request.readyState == 4) {
     // everything is good, the response is received
+
     // 一切 ok, 繼續解析
 
} else {
 
} else {
     // still not ready
+
     // 還沒完成
 
}
 
}
 
</pre>
 
</pre>
  
The full list of the <code>readyState</code> values is as follows:
+
<code>readyState</code> 所有可能的值如下:
* 0 (uninitialized)
+
* 0 (還沒開始)
* 1 (loading)
+
* 1 (讀取中)
* 2 (loaded)
+
* 2 (已讀取)
* 3 (interactive)
+
* 3 (資訊交換中)
* 4 (complete)
+
* 4 (一切完成)
([http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/readystate_1.asp Source])
+
([http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/readystate_1.asp 資料來源: MSDN])
  
The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html W3C site]. For our purposes we are only interested in <code>200 OK</code> response.
+
接下來要檢查伺服器傳回的 HTTP 狀態碼。所有狀態碼列表可於 [http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html W3C 網站]上查到,但我們要管的是 <code>200 OK</code> 這種狀態。
  
 
<pre>
 
<pre>
 
if (http_request.status == 200) {
 
if (http_request.status == 200) {
     // perfect!
+
     // 萬事具備
 
} else {
 
} else {
     // there was a problem with the request,
+
     // 似乎有點問題,或許伺服器傳回了 404 (查無此頁) 或者 500 (內部錯誤) 什麼的
    // for example the response may be a 404 (Not Found)
 
    // or 500 (Internal Server Error) response codes
 
 
}
 
}
 
</pre>
 
</pre>
  
Now after you've checked the state of the request and the HTTP status code of the response, it's up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:
+
檢查傳回的 HTTP 狀態碼後,要怎麼處理傳回的資料就由你決定了。有兩種存取資料的方式:
* <code>http_request.responseText</code> – will return the server response as a string of text
+
* <code>http_request.responseText</code> – 這樣會把傳回值當字串用
* <code>http_request.responseXML</code> – will return the response as an <code>XMLDocument</code> object you can traverse using the JavaScript DOM functions
+
* <code>http_request.responseXML</code> – 這樣會把傳回值視為 <code>XMLDocument</code> 物件,而後可用 JavaScript DOM 相關函式處理
  
 
== 第三步 - 萬事俱備 - 簡單範例 ==
 
== 第三步 - 萬事俱備 - 簡單範例 ==
  
Let's put it all together and do a simple HTTP request. Our JavaScript will request an HTML document, <code>test.html</code>, which contains the text "I'm a test." and then we'll <code>alert()</code> the contents of the <code>test.html</code> file.
+
好,接著就做一次簡單的 HTTP 範例,演示方才的各項技巧。這段 JavaScript 會向伺服器要一份裡頭有「I'm a test.」字樣的 HTML 文件(<code>test.html</code>),而後以 <code>alert()</code> 將文件內容列出。
  
 
<pre>
 
<pre>
行 160: 行 154:
 
</pre>
 
</pre>
  
In this example:
+
在此範例中:
* The user clicks the link "Make a request" in the browser;
+
* 首先使用者按下「Make a request」
* This calls the <code>makeRequest()</code> function with a parameter – the name <code>test.html</code> of an HTML file in the same directory;
+
* 這麼一來就會呼叫 <code>makeRequest()</code> 函式,亦傳入參數值 <code>test.html</code> (也就是那份 HTML 檔的名稱,放在同目錄下)
* The request is made and then (<code>onreadystatechange</code>) the execution is passed to <code>alertContents()</code>;
+
* 接著發出 request,而後會將主導權交給 <code>onreadystatechange</code> 指定的  <code>alertContents()</code> 函式
* <code>alertContents()</code> checks if the response was received and it's an OK and then <code>alert()</code>s the contents of the <code>test.html</code> file.
+
* <code>alertContents()</code> 檢查回應是否正常,而後以 <code>alert()</code> <code>test.html</code> 的內容列出
  
You can test the example [http://www.w3clubs.com/mozdev/httprequest_test.html here] and you can see the test file [http://www.w3clubs.com/mozdev/test.html here].
+
你可以[http://www.w3clubs.com/mozdev/httprequest_test.html 由此測試本例],也可以參考[http://www.w3clubs.com/mozdev/test.html 測試檔案]
  
 
== 第四步 – 「X 檔案」(又稱為「處理 XML 回應值」) ==
 
== 第四步 – 「X 檔案」(又稱為「處理 XML 回應值」) ==
  
In the previous example, after the response to the HTTP request was received, we used the <code>reponseText</code> property of the request object and it contained the contents of the <code>test.html</code> file. Now let's try the <code>responseXML</code> property.
+
前面的例子中,在收到 HTTP 傳回值後我們以物件的 <code>reponseText</code> 屬性使用 <code>test.html</code> 檔案的內容,接著來試試 <code>responseXML</code> 屬性的方法。
  
First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:
+
首先,我們得做個格式正確的 XML 文件,以便稍後取用。此檔名喚 <code>test.xml</code>,內容如下:
  
 
<pre>
 
<pre>
行 181: 行 175:
 
</pre>
 
</pre>
  
In the script we only need to change the request line with:
+
在程式中,我們叫用檔案的地方只須略事修改如下:
  
 
<pre>
 
<pre>
行 189: 行 183:
 
</pre>
 
</pre>
  
Then in <code>alertContents()</code> we need to replace the <code>alert()</code>-ing line <code>alert(http_request.responseText);</code> with:
+
接著在 <code>alertContents()</code> 中,我們必須將 <code>alert(http_request.responseText);</code> 改成這樣:
  
 
<pre>
 
<pre>
行 197: 行 191:
 
</pre>
 
</pre>
  
This way we took the <code>XMLDocument</code> object given by <code>responseXML</code> and we used DOM methods to access some data contained in the XML document. You can see the <code>test.xml</code> [http://www.w3clubs.com/mozdev/test.xml here] and the updated test script [http://www.w3clubs.com/mozdev/httprequest_test_xml.html here].
+
這樣一來我們便可取得 <code>responseXML</code> 所傳回的 <code>XMLDocument</code> 物件,而後以 DOM 相關的方法取用 XML 文件內容。你可以參考 [http://www.w3clubs.com/mozdev/test.xml<code>test.xml</code> 的原始碼] 以及修改過後的[http://www.w3clubs.com/mozdev/httprequest_test_xml.html 測試程式]
 +
 
 +
其他與 DOM 相關的方法,請參考 [http://www.mozilla.org/docs/dom/ Mozilla DOM] 文件。
 +
 
 +
<div style="display:none;">
 +
[[{{literal2|=Category:文件專案|文件專案=}}|{{literal2|={{PAGENAME}}|文件專案=}}]]
 +
[[{{literal2|=Category:{{{4}}}|{{{4}}}=}}|{{literal2|={{PAGENAME}}|{{{4}}}=}}]]
 +
[[{{literal2|=Category:{{{5}}}|{{{5}}}=}}|{{literal2|={{PAGENAME}}|{{{5}}}=}}]]
 +
[[{{literal2|=Category:{{{6}}}|{{{6}}}=}}|{{literal2|={{PAGENAME}}|{{{6}}}=}}]]
 +
</div>
  
For more on the DOM methods, be sure to check [http://www.mozilla.org/docs/dom/ Mozilla's DOM implementation] documents.
+
<div class="page-nav"><b>‧返回上一頁: </b>[[開發人員文件主頁]]</div>

於 2009年11月25日 (三) 13:12 的最新修訂

本文已經移往 Mozilla 開發者中心,請前往目前網址參考最新資訊。

這篇文章說明 AJAX 相關技術的基礎,並提供實例供您上手。


第一步 – 說聲「請」 (又稱為「怎麼發出 XMLHttpRequest」)

為了用 JavaScript 對伺服器發送 HTTP 要求,必須先以相關的類別(class)製出實體(instance)。Internet Explorer 首先以 ActiveX 物件方式提供 XMLHTTP 類別,而 Mozilla、Safari 及其他瀏覽器則隨後以 XMLHttpRequest 類別支援此 ActiveX 物件中的類別及屬性。

因此,如果想跨瀏覽器,那麼可以這麼寫:

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
}

(由於這段程式僅供說明,所以是採最簡方式寫出。本文第三步中有另一種我們比較常用的寫法。)

有些版本的 Mozilla 瀏覽器在伺服器送回的資料未含 XML mime-type 檔頭(header)時會出錯。為了避免這個問題,你可以用下列方法覆寫伺服器傳回的檔頭,以免傳回的不是 text/xml

http_request = new XMLHttpRequest();
http_request.overrideMimeType('text/xml');

接下來是要決定伺服器傳回資料後的處理方式,此時你只要以 onreadystatechange 這個屬性指明要處理傳回值的 JavaScript 函式名稱即可,例如:

http_request.onreadystatechange = nameOfTheFunction;

注意,指定的函式名稱後不加括號也沒有參數。除了指定函式名稱外,你也能用 Javascript 即時定義函式的方法來定一個新的處理函式,如下:

http_request.onreadystatechange = function(){
    // 做些事
};

決定處理方式之後你得確實發出 request,此時需叫用 HTTP request 類別的 open()send() 方法,如下:

http_request.open('GET', 'http://www.example.org/some.file', true);
http_request.send(null);
  • open() 的第一個參數是 HTTP request 的方法,也就是從 GET、POST、HEAD 中擇一使用,亦可用你主機上支援的方式。為遵循 HTTP 標準,請記得這些方法都是大寫,不然有的瀏覽器(如 Firefox)或許不會理你。其他 HTTP request 可以支援的方法列表請參考 W3C 規格書
  • 第二個參數是目標 URL。基於安全考量,你不能叫用同網域以外的網頁。如果網域不同,則叫用 open() 時會出現「權限不足,拒絕存取」那類的錯誤。通常大夥會犯的錯誤多為在 domain.tld 網的網站下呼叫 www.domain.tld 中的網頁,僅是一點點差別都不行。
  • 第三個參數決定此 request 是否不同步進行,如果設定為 TRUE 則即使伺服器尚未傳回資料也會繼續執行其餘的程式,這也就是 AJAX 中第一個 A 代表的意義。

send() 的參數在以 POST 發出 request 時可以是任何想傳給伺服器的東西,而資料則以查詢字串的方式列出,例如:

name=value&anothername=othervalue&so=on

不過如果你想要以 POST 方式傳送資料,則必須先將 MIME 型態改好,如下:

http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

否則伺服器就不會理你傳過來的資料了。

第二步 – 「就上咩!」(又稱為「處理伺服器傳回的資料」)

傳出 request 時必須提供處理傳回值的函式名稱。

http_request.onreadystatechange = nameOfTheFunction;

那麼來看看這個函式該做些什麼。首先,它必須檢查 request 目前的狀態:如果狀態值為 4 代表伺服器已經傳回所有資訊了,便可以開始解析所得資訊。

if (http_request.readyState == 4) {
    // 一切 ok, 繼續解析
} else {
    // 還沒完成
}

readyState 所有可能的值如下:

  • 0 (還沒開始)
  • 1 (讀取中)
  • 2 (已讀取)
  • 3 (資訊交換中)
  • 4 (一切完成)

(資料來源: MSDN)

接下來要檢查伺服器傳回的 HTTP 狀態碼。所有狀態碼列表可於 W3C 網站上查到,但我們要管的是 200 OK 這種狀態。

if (http_request.status == 200) {
    // 萬事具備
} else {
    // 似乎有點問題,或許伺服器傳回了 404 (查無此頁) 或者 500 (內部錯誤) 什麼的
}

檢查傳回的 HTTP 狀態碼後,要怎麼處理傳回的資料就由你決定了。有兩種存取資料的方式:

  • http_request.responseText – 這樣會把傳回值當字串用
  • http_request.responseXML – 這樣會把傳回值視為 XMLDocument 物件,而後可用 JavaScript DOM 相關函式處理

第三步 - 萬事俱備 - 簡單範例

好,接著就做一次簡單的 HTTP 範例,演示方才的各項技巧。這段 JavaScript 會向伺服器要一份裡頭有「I'm a test.」字樣的 HTML 文件(test.html),而後以 alert() 將文件內容列出。

<script type="text/javascript" language="javascript">

    var http_request = false;

    function makeRequest(url) {

        http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = alertContents;
        http_request.open('GET', url, true);
        http_request.send(null);

    }

    function alertContents() {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                alert(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }

    }
</script>
<span
    style="cursor: pointer; text-decoration: underline"
    onclick="makeRequest('test.html')">
        Make a request
</span>

在此範例中:

  • 首先使用者按下「Make a request」
  • 這麼一來就會呼叫 makeRequest() 函式,亦傳入參數值 test.html (也就是那份 HTML 檔的名稱,放在同目錄下)
  • 接著發出 request,而後會將主導權交給 onreadystatechange 指定的 alertContents() 函式
  • alertContents() 檢查回應是否正常,而後以 alert()test.html 的內容列出

你可以由此測試本例,也可以參考測試檔案

第四步 – 「X 檔案」(又稱為「處理 XML 回應值」)

前面的例子中,在收到 HTTP 傳回值後我們以物件的 reponseText 屬性使用 test.html 檔案的內容,接著來試試 responseXML 屬性的方法。

首先,我們得做個格式正確的 XML 文件,以便稍後取用。此檔名喚 test.xml,內容如下:

<?xml version="1.0" ?>
<root>
    I'm a test.
</root>

在程式中,我們叫用檔案的地方只須略事修改如下:

...
onclick="makeRequest('test.xml')">
...

接著在 alertContents() 中,我們必須將 alert(http_request.responseText); 改成這樣:

var xmldoc = http_request.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

這樣一來我們便可取得 responseXML 所傳回的 XMLDocument 物件,而後以 DOM 相關的方法取用 XML 文件內容。你可以參考 test.xml 的原始碼 以及修改過後的測試程式

其他與 DOM 相關的方法,請參考 Mozilla DOM 文件。

[[Category:{{{4}}}|AJAX 上手篇]] [[Category:{{{5}}}|AJAX 上手篇]] [[Category:{{{6}}}|AJAX 上手篇]]

個人工具