标签:自动联想搜索提示功能
<script type="text/javascript"> //定义当前页面的url地址 var currentUrl = "<?=urldecode(Url::toRoute([‘/article/default/index‘]))?>"; var AutoComplete = "<?=urldecode(Url::toRoute([‘/article/default/autocomplete‘]))?>"; var repositorytypehandle= "<?=urldecode(Url::toRoute([‘/article/default/handle‘]))?>"; </script> <input type="hidden" name="kws" value="" /> <input id="ids" type="hidden" name="ids" value="" class="form-control"> <input id="choxq" name="choxq" type="text" class="kwarticle form-control inline" autocomplete="off" placeholder="请输入关键词进行搜索"> <ul class="choul" style="display: none"> </ul> :
$(".kwarticle").keyup(function (){ var q = $.trim($(".kwarticle").val()); var id="<?=$id?>" var pId="<?=$pId?>" $(‘[name="kws"]‘).val(q); if (!q) { $(".choul").css("display", "none"); return false; } var data = "&q="+q+"&id="+id+"&pId="+pId; $.ajax({ url: AutoComplete, data: data, type: ‘GET‘, dataType: ‘json‘, timeout: 1000, cache: false, success: succFunction //鎴愬姛鎵ц鏂规硶 }); function succFunction(tt) { $(".choul").html(‘‘); var json = eval(tt); //鏁扮粍 // alert(tt); $.each(json, function (index, item) { //寰幆鑾峰彇鏁版嵁 var name = json[index].title; var id = json[index].id; $(".choul").append("<li data="+id+">"+name+"</li>"); }); if (json.length== 1) { //寰幆鑾峰彇鏁版嵁 var name = json[0].title; var id = json[0].id; $(‘[name="ids"]‘).val(id); } } $(".choul").css("display", "block"); }); $(document).on("click",".choul li",function () { $(".kwarticle").val($(this).text()); $(".choul").css("display", "none"); var selectvalue=$(this).text(); var id=$(this).attr(‘data‘); $(‘[name="ids"]‘).val(id); $(‘[name="choxq"]‘).val(selectvalue); })
public function actionAutocomplete(){
$this->layout = false;
$q = Yii::$app->request->get(‘q‘);//联想输入词
$params = Yii::$app->request->get();
if(empty($q)){
$output = array(
‘status‘ => 2,
‘tips‘ => ‘暂无数据‘,
‘data‘ => array(),
);
echo json_encode($output);
exit;
} else{
$query=Article::find();
$query->select(‘*‘);
if(!empty($params[‘id‘])&&empty($params[‘pId‘])){//取主分类下面的所有子分类文章且不是搜索过来的情况
$sonlist=\app\models\RepositoryType::find()->where([‘pId‘=>$params[‘id‘]])->asArray()->all();
$arr=‘‘;
foreach($sonlist as $k=>$v){
$arr.=‘,‘.$v[‘id‘];
}
$query->where([‘repositoryId‘=>explode(‘,‘,$arr)]);
}elseif(!empty($params[‘id‘])&&!empty($params[‘pId‘])){
$query->where([‘repositoryId‘=>$params[‘id‘]]);
}
$query->andWhere([‘isDel‘=>2]);
$query->orderBy(‘createTime desc‘);
$query->asArray();
$data=$query->all();
// $data = Article::find()->where([‘like‘,‘title‘,$q])->asArray()->all();
if (!empty($data)) {
$output = array(
‘status‘ => 1,
‘tips‘ => ‘‘,
‘data‘ => $data,
);
} else{
$output = array(
‘status‘ => 2,
‘tips‘ => ‘暂无数据‘,
‘data‘ => array(),
);
}
header(‘Content-Type:application/json; charset=utf-8‘);
exit(json_encode($data,0));
}
}
本文出自 “PHP/Linux@HeFei” 博客,请务必保留此出处http://liang3391.blog.51cto.com/178205/1976283
标签:自动联想搜索提示功能
原文地址:http://liang3391.blog.51cto.com/178205/1976283