本文实例讲述了PHP+JS实现的实时搜索提示功能。分享给大家供大家参考,具体如下:效果图
本文实例讲述了PHP+JS实现的实时搜索提示功能。分享给大家供大家参考,具体如下:
效果图如下:
代码如下:
HTML代码:(该代码用两种方法实现,一种Jquery,一种原生JS)
<html>
<head>
<script src="/DelphiRequest/search/js/jquery.js"></script>
<script>
/*用原生js实现
// function showResult(str)
// {
// if (str.length==0)
// {
// document.getElementById("livesearch").innerHTML="";
// document.getElementById("livesearch").style.border="0px";
// 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("livesearch").innerHTML=xmlhttp.responseText;
// document.getElementById("livesearch").style.border="1px solid #A5ACB2";
// }
// }
// xmlhttp.open("GET","livesearch.php?q="+str,true);
// xmlhttp.send();
// }
*/
//用jquery实现
function showResult(str){
$.ajax({
type: "GET",
url : "livesearch.php",
datatype : 'json',
data: {'q':str} ,
success :function (data) {
document.getElementById("livesearch").innerHTML=data;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
})
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>
PHP代码如下:(PHP不仅可以考虑直接使用数组,也可以考虑直接查询数据库,获取数据库内容,本代码使用的是数组。)
<?php
$provinces=array("beijing","tianjin","shanghai","chongqing","hebei","henan","heilongjiang","jilin","changchun",
"shandong","anhui","shanxi","guangzhou","yunnan","hainan","xizang","qinghai","fujian","guizhou","jiangsu",
"zhejiang","guangzhou","yunan","hainan","xizang","neimenggu","sichuan","gansu","ningxia","xianggang","aomen");
$tmp=$_GET['q'];
$val=array();
$k=0;
if (strlen($tmp)>0)
{
for($i=0;$i<31;$i++){
if(strpos($provinces[$i],$tmp)!==false){
//传递值给val
$val[$k]=$provinces[$i];
//下标增加
$k=$k+1;
}
}
//遍历val数组
for($j=0;$j<count($val);$j++)
{
echo $val[$j];
echo "<br>";
}
}
?>
PHP
JS
实时搜索
提示