Hello! Ajax!

來撰寫您第一個Ajax程式,使用非同步的方式向伺服端取得文字檔案,並加以顯示,首先請準備一個HTML網頁:

HelloAjaxEx-1.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>  <meta content="text/html; charset=Big5" http-equiv="content-type">  <title>Hello! Ajax! Examples...</title>  <script type="text/javascript" src="HelloAjaxEx-1.js"></script></head><body><center><input value="Ajax請求" onclick="startRequest();" type="button"></center></body></html>

這個HTML網頁會取得JavaScript檔案,而按下按鈕後,會執行startRequest()函式,JavaScript檔案如下所示:

HelloAjaxEx-1.js
var xmlHttp;function createXMLHttpRequest() {    if(window.XMLHttpRequest) {        xmlHttp = new XMLHttpRequest();    }    else if(window.ActiveXObject) {        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");    }}function startRequest() {    createXMLHttpRequest();    xmlHttp.onreadystatechange = handleStateChange;    xmlHttp.open("GET", "HelloAjaxEx-1.txt");    xmlHttp.send(null);}function handleStateChange() {    if(xmlHttp.readyState == 4) {        if(xmlHttp.status == 200) {            alert("伺服端回應:" + xmlHttp.responseText);        }    }}

在startRequest()中會建立XMLHttpRequest,並發出非同步請求取得HelloAjaxEx-1.txt,在當中只是簡單的文字訊息,注意如果當中要撰寫中文,則文字檔案必須儲存為UTF8,假設HelloAjaxEx1.txt如下撰寫:

HelloAjaxEx1.txt
這是非同步請求的回應文字

您可以按下 鏈結 來觀看結果。

您可以結合DOM來顯示取得的回應文字,不必使用對話方塊或重清(Refresh)網頁,例如在網頁中設定一個<div>:

HelloAjaxEx-2.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>  <meta content="text/html; charset=Big5" http-equiv="content-type">  <title>Hello! Ajax! Examples...</title>  <script type="text/javascript" src="HelloAjaxEx-2.js"></script></head><body><center><input value="Ajax請求" onclick="startRequest();" type="button"><br><div id="response"></div></center></body></html>

而HelloAjaxEx-2.js可以改寫如下:

HelloAjaxEx-2.js
var xmlHttp;function createXMLHttpRequest() {    if(window.XMLHttpRequest) {        xmlHttp = new XMLHttpRequest();    }    else if(window.ActiveXObject) {        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");    }}function startRequest() {    createXMLHttpRequest();    xmlHttp.onreadystatechange = handleStateChange;    xmlHttp.open("GET", "HelloAjaxEx-2.txt");    xmlHttp.send(null);}function handleStateChange() {    if(xmlHttp.readyState == 4) {        if(xmlHttp.status == 200) {            document.getElementById("response").innerHTML =                xmlHttp.responseText;        }    }}

 

在這邊為了簡化範例,直接使用DOM物件的innerHTML屬性,您可以按 鏈結 觀看結果。

posted @ 2009-07-15 21:48  芋头  阅读(108)  评论(0编辑  收藏  举报