要想把請求發送到服務器,我們就需要使用 open() 方法和 send() 方法。
open() 方法需要三個參數。第一個參數定義發送請求所使用的方法(get 還是 post)。第二個參數規定服務器端腳本的 url。第三個方法規定應當對請求進行異步地處理。
send() 方法可將請求送往服務器。如果我們假設 html 文件和 asp 文件位于相同的目錄,那么代碼是這樣的:
xmlhttp.open("get","time.asp",true);xmlhttp.send(null);
現在,我們必須決定何時執行 ajax 函數。當用戶在用戶名文本框中鍵入某些內容時,我們會令函數“在幕后”執行。
<html><body><script type="text/javascript">function ajaxfunction() { var xmlhttp; try { // firefox, opera 8.0+, safari xmlhttp=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">用戶: <input type="text" name="username" onkeyup="ajaxfunction();" />時間: <input type="text" name="time" /></form></body></html>下一節介紹 "time.asp" 的腳本,這樣我們完整的 ajax 應用程序就搞定了。
新聞熱點
疑難解答
圖片精選