舊文件

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

AJAX 上手篇

出自 MozTW Wiki

於 2005年9月27日 (二) 01:46 由 BobChao對話 | 貢獻 所做的修訂 第一步 – 說聲「請」 (又稱為「怎麼發出 XMLHttpRequest」)


編譯中: --BobChao 19:48 2005年九月21日 (CST)

這篇文章說明 AJAX 相關技術的基礎,並提供實例供您上手。本文編譯自 AJAX:Getting Started,在 devmo 有中文版之後可能會移過去。

AJAX 是啥?

AJAX (Asynchronous JavaScript and XML, 非同步 JavaScript 及 XML 技術) 是個新詞,但內涵是兩個存在已有一段時間的 JavaScript 功能。這兩種功能以往一直被忽略,在 Gmail、Google suggest 及 Google Maps 出現後才一舉成名天下知。

這兩個 JavaScript 功能是:

  • 在不重新讀取頁面的情況下對伺服器送出要求(request)
  • 解析、使用 XML 文件

第一步 – 說聲「請」 (又稱為「怎麼發出 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 規格書
  • 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.
  • The third parameter sets whether the request is asynchronous. If TRUE, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.

The parameter to the send() 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:

name=value&anothername=othervalue&so=on

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

Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.

http_request.onreadystatechange = nameOfTheFunction;

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.

if (http_request.readyState == 4) {
    // everything is good, the response is received
} else {
    // still not ready
}

The full list of the readyState values is as follows:

  • 0 (uninitialized)
  • 1 (loading)
  • 2 (loaded)
  • 3 (interactive)
  • 4 (complete)

(Source)

The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the W3C site. For our purposes we are only interested in 200 OK response.

if (http_request.status == 200) {
    // perfect!
} else {
    // there was a problem with the request,
    // for example the response may be a 404 (Not Found)
    // or 500 (Internal Server Error) response codes
}

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_request.responseText – will return the server response as a string of text
  • http_request.responseXML – will return the response as an XMLDocument object you can traverse using the JavaScript DOM functions

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

Let's put it all together and do a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." and then we'll alert() the contents of the test.html file.

<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>

In this example:

  • The user clicks the link "Make a request" in the browser;
  • This calls the makeRequest() function with a parameter – the name test.html of an HTML file in the same directory;
  • The request is made and then (onreadystatechange) the execution is passed to alertContents();
  • alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file.

You can test the example here and you can see the test file here.

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

In the previous example, after the response to the HTTP request was received, we used the reponseText property of the request object and it contained the contents of the test.html file. Now let's try the responseXML property.

First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:

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

In the script we only need to change the request line with:

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

Then in alertContents() we need to replace the alert()-ing line alert(http_request.responseText); with:

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

This way we took the XMLDocument object given by responseXML and we used DOM methods to access some data contained in the XML document. You can see the test.xml here and the updated test script here.

For more on the DOM methods, be sure to check Mozilla's DOM implementation documents.

個人工具