標籤:body key action send == utf-8 url 網頁 php
AJAX 最大的優點是在不重新載入整個頁面的情況下,可以與伺服器交換資料並更新部分網頁內容。
<head><meta charset="utf-8"><script>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();}</script></head><body><h3>在輸入框中嘗試輸入字母 a:</h3><form action=""> 輸入姓名: <input type="text" id="txt1" onkeyup="showHint(this.value)" /></form><p>提示資訊: <span id="txtHint"></span></p>
如果輸入框不為空白,showHint() 函數執行以下任務:
- 建立 XMLHttpRequest 對象
- 當伺服器響應就緒時執行函數
- 把請求發送到伺服器上的檔案
- 請注意我們向 URL 添加了一個參數 q (帶有輸入框的內容)
gethint.php:
<?php// Fill up array with names$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[]="Tove";$a[]="Unni";$a[]="Violet";$a[]="Liza";$a[]="Elizabeth";$a[]="Ellen";$a[]="Wenche";$a[]="Vicky";//get the q parameter from URL$q=$_GET["q"];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]; } } }}if ($hint == ""){ $response="no suggestion";}else{ $response=$hint;}//output the responseecho $response;?>
AJAX非同步實現