我們已看到 ajax 可被用來創(chuàng)建更多交互性的應用程序。
在下面的 ajax 例子中,我們會演示當用戶向一個標準的 html 表單中輸入數(shù)據(jù)時網(wǎng)頁如何與 web 服務器進行通信。
suggestions:
表單的 html 代碼:
<form> first name:<input type="text"id="txt1"
onkeyup="showhint(this.value)"
/></form><p>suggestions: <spanid="txthint"
></span></p>
正如您看到的,這是一個簡單的帶有名為 "txt1" 輸入域的 html 表單。輸入域的事件屬性定義了一個由 onkeyup 事件觸發(fā)的函數(shù)。
表單下面的段落包含了一個名為 "txthint" 的 span,這個 span 充當了由 web 服務器所取回的數(shù)據(jù)的位置占位符。
當用戶輸入數(shù)據(jù)時,名為 "showhint()" 的函數(shù)就會被執(zhí)行。函數(shù)的執(zhí)行是由 "onkeyup" 事件觸發(fā)的。另外需要說明的是,當用戶在文本域中輸入數(shù)據(jù)時把手指從鍵盤按鍵上移開時,函數(shù) showhint 就會被調(diào)用。
showhint() 函數(shù)是一個位于 html 頁面 head 部分的很簡單的 javascript 函數(shù)。
此函數(shù)包含以下代碼:
function showhint(str){ if (str.length==0
) { document.getelementbyid("txthint").innerhtml=""; return; } xmlhttp=getxmlhttpobject() if (xmlhttp==null) { alert ("您的瀏覽器不支持ajax!"); return; }varurl
="gethint.asp";url=url+"?q
="+str;url=url+"&sid
="+math.random();xmlhttp.onreadystatechange=statechanged
;xmlhttp.open("get",url,true);xmlhttp.send(null);}
每當有字符輸入文本框時,此函數(shù)就會執(zhí)行。
假如文本域中存在某些輸入,函數(shù)就會執(zhí)行:
上面的例子可調(diào)用名為 getxmlhttpobject() 的函數(shù)。
此函數(shù)的作用是解決為不同瀏覽器創(chuàng)建不同的 xmlhttp 對象的問題。
這是此函數(shù)的代碼:
function getxmlhttpobject(){ var xmlhttp=null; try { // firefox, opera 8.0+, safari xmlhttp=new xmlhttprequest(); } catch (e) { // internet explorer try { xmlhttp=new activexobject("msxml2.xmlhttp"); } catch (e) { xmlhttp=new activexobject("microsoft.xmlhttp"); } } return xmlhttp;}
statechanged() 函數(shù)包含下面的代碼:
function statechanged() { if (xmlhttp.readystate==4) { document.getelementbyid("txthint").innerhtml=xmlhttp.responsetext
; }}
每當 xmlhttp 對象的狀態(tài)發(fā)生改變時,statechanged() 函數(shù)就會執(zhí)行。
當狀態(tài)變更為 4(“完成”)時,txthint 占位符的內(nèi)容就被響應文本來填充。
新聞熱點
疑難解答
圖片精選