ASP - AJAX 與 ASP
AJAX 用于創(chuàng)建動態(tài)性更強的應(yīng)用程序。
AJAX ASP 實例
下面的例子將演示當(dāng)用戶在輸入框中鍵入字符時,網(wǎng)頁如何與服務(wù)器進行通信:
實例
請在下面的輸入框中鍵入字母(A - Z):
建議:
實例解釋 - HTML 頁面
當(dāng)用戶在上面的輸入框中鍵入字符時,會執(zhí)行 "showHint()" 函數(shù)。該函數(shù)由 "onkeyup" 事件觸發(fā):
<!DOCTYPE html> <html> <head> <script> function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// 針對 IE7+, Firefox, Chrome, Opera, Safari 的代碼 xmlhttp=new XMLHttpRequest(); } else {// 針對 IE6, IE5 的代碼 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","gethint.asp?q="+str,true); xmlhttp.send(); } </script> </head <body> <p><b>請在輸入框中輸入英文字符:</b></p> <form> First name: <input type="text" onkeyup="showHint(this.value)" size="20"> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>
源代碼解釋:
如果輸入框是空的(str.length==0),該函數(shù)會清空占位符 txtHint 的內(nèi)容,并推出該函數(shù)。
如果輸入框不是空的,那么 showHint() 會執(zhí)行以下步驟:
- 創(chuàng)建 XMLHttpRequest 對象
- 創(chuàng)建在服務(wù)器響應(yīng)就緒時執(zhí)行的函數(shù)
- 向服務(wù)器上的文件發(fā)送請求
- 請注意添加到 URL 末端的參數(shù)(q)(包含輸入框的內(nèi)容)
ASP 文件
上面這段 JavaScript 調(diào)用的服務(wù)器頁面是名為 "gethint.asp" 的 ASP 文件。
"gethint.asp" 中的源代碼會檢查姓名數(shù)組,然后向瀏覽器返回對應(yīng)的姓名:
<% response.expires=-1 dim a(30) 'Fill up array with names a(1)="Anna" a(2)="Brittany" a(3)="Cinderella" a(4)="Diana" a(5)="Eva" a(6)="Fiona" a(7)="Gunda" a(8)="Hege" a(9)="Inga" a(10)="Johanna" a(11)="Kitty" a(12)="Linda" a(13)="Nina" a(14)="Ophelia" a(15)="Petunia" a(16)="Amanda" a(17)="Raquel" a(18)="Cindy" a(19)="Doris" a(20)="Eve" a(21)="Evita" a(22)="Sunniva" a(23)="Tove" a(24)="Unni" a(25)="Violet" a(26)="Liza" a(27)="Elizabeth" a(28)="Ellen" a(29)="Wenche" a(30)="Vicky" '從 URL 獲得參數(shù) q q=ucase(request.querystring("q")) '如果長度 q>0,則從數(shù)組中查找所有提示 if len(q)>0 then hint="" for i=1 to 30 if q=ucase(mid(a(i),1,len(q))) then if hint="" then hint=a(i) else hint=hint & " , " & a(i) end if end if next end if '如果未找到提示,則輸出 "no suggestion" 'or output the correct values if hint="" then response.write("no suggestion") else response.write(hint) end if %>
源代碼解釋:
如果 JavaScript 發(fā)送了任何文本(即 strlen($q) 大于 0),則會發(fā)生:
- 查找匹配來自 JavaScript 的字符的姓名
- 如果未找到匹配,則將響應(yīng)字符串設(shè)置為 "no suggestion"
- 如果找到一個或多個匹配姓名,則用所有姓名設(shè)置響應(yīng)字符串
- 把響應(yīng)發(fā)送到占位符 "txtHint"