要想把請(qǐng)求發(fā)送到服務(wù)器,我們就需要使用 open() 方法和 send() 方法。
open() 方法需要三個(gè)參數(shù)。第一個(gè)參數(shù)定義發(fā)送請(qǐng)求所使用的方法(GET 還是 POST)。第二個(gè)參數(shù)規(guī)定服務(wù)器端腳本的 URL。第三個(gè)方法規(guī)定應(yīng)當(dāng)對(duì)請(qǐng)求進(jìn)行異步地處理。
send() 方法可將請(qǐng)求送往服務(wù)器。如果我們假設(shè) HTML 文件和 ASP 文件位于相同的目錄,那么代碼是這樣的:
xmlHttp.open
("GET","time.asp",true); xmlHttp.send
(null);
現(xiàn)在,我們必須決定何時(shí)執(zhí)行 AJAX 函數(shù)。當(dāng)用戶(hù)在用戶(hù)名文本框中鍵入某些內(nèi)容時(shí),我們會(huì)令函數(shù)“在幕后”執(zhí)行。
<html> <body> <script type="text/javascript"> function ajaxFunction() { varxmlHttp
; try { // Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();
} catch (e) { // Internet Explorer try {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { try {xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { alert("您的瀏覽器不支持AJAX!"); return false; } } } xmlHttp.onreadystatechange
=function() { if(xmlHttp.readyState
==4) { document.myForm.time.value=xmlHttp.responseText
; } } xmlHttp.open("GET","time.asp",true)
; xmlHttp.send(null)
; } </script> <form name="myForm"> 用戶(hù): <input type="text" name="username"onkeyup="ajaxFunction();"
/> 時(shí)間: <input type="text" name="time" /> </form> </body> </html>
下一節(jié)介紹 "time.asp" 的腳本,這樣我們完整的 AJAX 應(yīng)用程序就搞定了。