Hello! Ajax!

来源:互联网 发布:高速网络链路 编辑:程序博客网 时间:2024/06/09 19:49

具体请点击:http://www.verydemo.com/demo_c107_i2747.html

來撰寫您第一個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></head><body><center></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></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) {        }    }}

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