日期:2014-05-16  浏览次数:20681 次

利用MVC框架和Ajax(完成类似百度搜索建议)

userController.class.php文件
public function showInterfaceAction(){
$this->smarty->display('baidu.tpl');
}
public function baiduSuggestAction(){
//命令模型层处理数据
$data = $_REQUEST['val'];
$userModel = new userModel('localhost','xuefei','root','123');
$row = $userModel->selectAll($data);
echo json_encode($row);
//命令视图层显示数据
}
userModel.class.php文件
public function selectAll($data){
$sql = "select * from qf where stu_name 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].stu_name+"</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>