PHP - ตัวอย่างการค้นหาข้อมูล array โดยใช้ AJAX |
|
Tuesday, 07 September 2010 16:23
|
|
ตัวอย่างโค้ด PHP การค้นหาข้อมูล array โดยใช้ AJAX <html> <head> <script type="text/javascript"> function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for 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","getarray.php?q="+str,true); xmlhttp.send(); } </script> </head <body> <p><b>ค้นหาชื่อ โดยพิมพ์ชื่อ (ตัวอักษร) ในช่องข้างล่างนี้</b></p> <form> ชื่อ : <input type="text" onkeyup="showHint(this.value)" size="20" /> </form> <p>คำที่ค้นพบ: <span id="txtHint"></span></p> </body> </html> ตัวอย่างไฟล์ PHP : getarray.php <?php // Fill up array with names $a[]="กรรณิกา"; $a[]="ขนิษฐา"; $a[]="คนึงนิจ"; $a[]="งุนงง"; $a[]="จารุวรรณ"; $a[]="ฉัตรชฏา"; $a[]="ชนิดา"; $a[]="ซาบซึ้ง"; $a[]="เฌอมาลย์"; $a[]="ญานี"; $a[]="ญาติ"; $a[]="Darin"; $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"; //get the q parameter from URL $q=$_GET["q"]; //lookup all hints from array if length of 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]; } } } } // กำหนดข้อความ "ไม่พบชื่อใดใด" เมื่อไม่พบชื่อที่ค้นหา // or to the correct values if ($hint == "") { $response="ไม่พบชื่อใดใด"; } else { $response=$hint; } //output the response echo $response; ?> To view rest of this section, please login or register.. ในการดูส่วนที่เหลือกรุณาเข้าสู่ระบบหรือลงทะเบียน.. |