本文实例讲述了thinkPHP+mysql+ajax实现的仿百度一下即时搜索效果。分享给大家供大家参考,具体如下:

用过百度搜索的人应该都知道这个效果,今天我用ThinkPHP+Mysql+Ajax来实现这样的一个效果,首先我把所有的代码都先给大家,最后再来讲解。

百度即时搜索效果图

57861de95b749874f17ff18241a44f7e.png

运行效果图

dc585cdf9e2421c1d7e9b42b76beb821.png

数据库截图

城市表

f87c2073a78ee24cb1fd58dda6b86a11.png

学校表

95370151fba059bcb82c155a874b2ce7.png

控制层代码(SchoolController.class.php)

namespaceWechat\Controller;

useThink\Controller;

/**

*学校模块控制层

*/

classSchoolControllerextendsController{

//学校选择页面

publicfunctionindex(){

$County=D("County");

$School=D("School");

//获取所有的省份列表

$cityList=$County->where("pid=0")->order("sortdesc")->select();

//遍历省份数据,获取二级城市列表

foreach($cityListas$key=>$value){

$countyList[]=$County->where("pid=".$value['id'])->order("sortdesc")->select();

}

//如果url传过来省级编号,就保存,否则就默认山东为要显示的省份

if(!empty($_GET['cityid'])){

$cityid=$_GET['cityid'];

}else{

//6号代码山东的城市编号

$cityid=6;

}

//查询此省份编号中的所有城市

$countyList=$County->where("pid=".$cityid)->order("sortdesc")->select();

//查询城市中的所有学校

foreach($countyListas$key=>$value){

$countyList[$key]['school']=$School->where("cid=".$value['id'])->select();

}

//给视图层赋值

$this->assign("cityList",$cityList);

$this->assign("countyList",$countyList);

//显示视图层

$this->display();

}

//根据关键字进行查找

publicfunctionget_school_by_key(){

$key=$_POST['key'];//获取关键字

if(empty($key))

$this->ajaxReturn(array("flag"=>0,"data"=>array()));//如果关键字为空,就返回空数组

//查询学校

$School=D("School");

$where['name']=array("like","%".$key."%");

$schoolList=$School->where($where)->limit("6")->select();

if(empty($schoolList))

$this->ajaxReturn(array("flag"=>0,"data"=>array()));//如果数据为空,也返回空数组

$this->ajaxReturn(array("flag"=>1,"data"=>$schoolList));//返回学校列表

}

}

视图层代码(index.html)

选择所在学校

请选择您所在学校

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐