简单的Ajax应用实例
生活随笔
收集整理的這篇文章主要介紹了
简单的Ajax应用实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
從網頁前端輸入提示范圍內的字符,然后顯示從后臺返回的結果
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <script type="text/javascript"> function showHint(str) { var xmlhttp; if (str.length==0){ document.getElementById("txtHint").innerHTML="";return;} if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest();} else{// code for IE6, IE5xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");} xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById("txtHint").innerHTML=xmlhttp.responseText;}} xmlhttp.open("GET","ajax.php?q="+str,true); xmlhttp.send(); } </script> </head> <body><h3>請在以下的輸入框中鍵入字母(A - Z):</h3> <form action=""> 姓氏:<input type="text" id="txt1" οnkeyup="showHint(this.value)" /> </form> <p>建議:<span id="txtHint"></span></p> </body> </html>
假設輸入框為空 (str.length==0),則該函數清空 txtHint 占位符的內容,并退出函數。
假設輸入框不為空,showHint() 函數運行下面任務:
- 創建 XMLHttpRequest 對象
- 當server響應就緒時運行函數
- 把請求發送到server上的文件
- 請注意我們向 URL 加入�了一個參數 q (帶有輸入框的內容)
<?php // 用名字來填充數組 $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; $a[]="Liza"; $a[]="Elizabeth"; $a[]="Ellen"; $a[]="Wenche"; $a[]="Vicky";//獲得來自 URL 的 q 參數 $q=$_GET["q"];//假設 q 大于 0,則查找數組中的全部提示 if (strlen($q) > 0){$hint="";for($i=0; $i<count($a); $i++){if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))){if ($hint==""){$hint=$a[$i];}else{$hint=$hint." , ".$a[$i];}}}}// 假設未找到提示,則把輸出設置為 "no suggestion" // 否則設置為正確的值 if ($hint == ""){$response="no suggestion";} else{$response=$hint;}//輸出響應 echo $response; ?>
效果
打包下載
轉載于:https://www.cnblogs.com/hrhguanli/p/3957402.html
總結
以上是生活随笔為你收集整理的简单的Ajax应用实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Percona Xtrabackup备份
- 下一篇: 分治法求最大子数组