AJAX ASP/PHP
ajax asp/php 實例
ajax 用于創造動態性更強的應用程序。
ajax asp/php 實例
下面的例子將為您演示當用戶在輸入框中鍵入字符時,網頁如何與 web 服務器進行通信: 請在下面的輸入框中鍵入字母(a - z):
function showhint(str)
{
var xmlhttp;
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","/try/ajax/gethint.php?q="+str,true);
xmlhttp.send();
}
實例
在輸入框中嘗試輸入字母 a:
輸入姓名:提示信息:
實例解析 - showhint() 函數
當用戶在上面的輸入框中鍵入字符時,會執行函數 "showhint()" 。該函數由 "onkeyup" 事件觸發:
function showhint(str) { var xmlhttp;
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","/try/ajax/gethint.php?q="+str,true);
xmlhttp.send();}
源代碼解析:
如果輸入框為空 str.length==0,則該函數清空 txthint 占位符的內容,并退出函數。
如果輸入框不為空,showhint() 函數執行以下任務:
- 創建 xmlhttprequest 對象
- 當服務器響應就緒時執行函數
- 把請求發送到服務器上的文件
- 請注意我們向 url 添加了一個參數 q (帶有輸入框的內容)
ajax 服務器頁面 - asp 和 php
以上實例 javascript 調用的服務器頁面是 php 文件,名為 gethint.php。
下面,我們創建了兩個版本的服務器文件,一個用 asp 編寫,另一個用 php 編寫。
asp 文件
"gethint.asp" 中的源代碼會檢查一個名字數組,然后向瀏覽器返回相應的名字:
<% 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" 'get the q parameter from url q=ucase(request.querystring("q")) 'lookup all hints from array if length of q>0 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 'output "no suggestion" if no hint were found 'or output the correct values if hint="" then response.write("no suggestion") else response.write(hint) end if %>
php 文件
下面的代碼用 php 編寫,與上面的 asp 代碼作用是一樣的。
0 if (strlen($q) > 0) { $hint=""; for($i=0; $i