百度搜索建议的实现
首先我需要建一个baidu.tpl一下是源代码(我这个是在mvc框架下做的百度搜索,其中用到了ajax的知识,至于ajax的运用和作用我博客中会专门写到)
<html>
<head>
<script>
function init(){
document.getElementById('dv').style.display='none';//用于让div先隐藏。
}
function textAjax(obj){
var xhr;
if(window.ActiveXObject){
xhr=new ActiveXObject('Microsoft.XMLHTTP');
}
else if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
var url="index.php?c=user&a=baiduSuggest";
xhr.open('POST',url,true);
xhr.onreadystatechange=callback;
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("val="+obj);
function callback(){
if(xhr.readyState==4){
if(xhr.status==200){
var json=eval('('+xhr.responseText+')');
var str='';
document.getElementById('dv').style.display="block";
for(var i=0;i<json.length;i++){
str +="<span>"+json[i].username+"</span><br/>";
document.getElementById('dv').innerHTML=str;
}
}
}
}
}
</script>
</head>
<body onload="init()">
<center>
<h3>百度一次,你就知道</h3>
<table>
<tr>
<td>
<form action="#" method="post">
<input type="text" size="30" id="search" onkeyup="textAjax(this.value)" />
<div id="dv" align="left" style=" position:relative; background-color:#CCC; border:dashed #999"></div>
</td><td>
<input type="submit" value="搜索" size="10" />
</td>
</form>
</tr>
</table>
</center>
</body>
</html>
这是userController.class.php文件的代码(其中baseCotroller.class.php和baseModel.class.php都经过类的封装。至于如何引用我会单独的做一个mvc框架搭建的博客)
public function baiduAction(){
$this ->smarty ->display("baidu.tpl");
}
public function baiduSuggestAction(){
$data=$_REQUEST['val'];//file_put_contents('d:/t.txt',$data,FILE_APPEND);
$userModel=new userModel('localhost','root','123','ajax');
$rows=$userModel->selectAll($data);
$row= json_encode($rows);
echo $row;
}
以下是一个userModel.class.php
public function selectAll($data){
$sql="select * from user where username like '$data%'";
$result=mysql_query($sql);
$rows=array();
while($row=mysql_fetch_assoc($result)){
$rows[]=$row;
}
return $rows;
}