加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:01:42 所属栏目:百科 来源:网络整理
导读:userController.class.php文件 public function showInterfaceAction(){ $this-smarty-display('baidu.tpl'); } public function baiduSuggestAction(){ //命令模型层处理数据 $data = $_REQUEST['val']; $userModel = new userModel('localhost','xuefei','

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读