userController.class.php
public function baiduSuggestAction(){
//命令模型层处理数据
$data = $_REQUEST['val'];
$userModel = new userModel("localhost","root","123","xsxx");
$rows = $userModel ->selectAll($data);
//var_dump($rows);
//服务器想返回集合类的数据,需要使用json_encode()转化
file_put_contents("d://test.txt",json_encode($rows),FILE_APPEND);
echo json_encode($rows);
//命令视图层显示数据
}
userModel.class.php
<?php
class userModel extends baseModel{
public function selectAll($data){
$sql = "select * from stu where sname like '{$data}%'";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
return $rows;
}
}
baidu.tpl
<script>
function init(){
document.getElementById('dv').style.display = "none";
}
function startAjax(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 = '';
for(var i=0;i<json.length;i++){
str += "<span>"+json[i].sname+"</span><br/>";
document.getElementById("dv").style.display = "block";
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="startAjax(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>