您的位置:首页 > 其它

类似百度搜索建议

2013-03-13 19:34 351 查看
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>

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: