前端頁面:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>搜索</title>
</head>
<body>
<div class="zgz">請輸入(A-Z):<input type="text" value="GET"></div>
<div class="rep">姓名:</div><br><br>
<div class="zgzB">請輸入(A-Z):<input type="text" value="POST"></div>
<div class="repB">姓名:</div>
<script src="js/jquery.min.js"></script>
<script>
$(function(){
var oBtn=$('.zgz input');
var oDiv=$('.rep');
var oBtnB=$('.zgzB input');
var oDivB=$('.repB');
oBtn.click(function(){$(this).val('')})
oBtn.keyup(function(){
$.ajax({
type:"get",//ajax請求方式(只有兩種:get/post)
data:{q:oBtn.val()},//傳給服務器的數據(json格式).
url:"php1.php",//ajax請求地址(將data的數據發送給(php1.php),后臺獲得數據進行處理,處理完再返還給前臺)
success: function(dat){//對響應回來(后臺返還回來)的數據進行處理
oDiv.html("姓名:");
oDiv.append(dat);
}
});
});
});
</script>
</body>
</html>
后臺(php):
<?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;
?>
?