当前位置:首页 > PHP教程 > PHP常见问题

Yii框架结合sphinx,Ajax实现搜索分页功能示例

本文实例讲述了yii框架结合sphinx,ajax实现搜索分页功能的方法。分享给大家供大家参考,具体如下:

效果图:

控制器:

<?php namespace backendcontrollers; use yii; use yiiwebcontroller; use yiidatapagination; use sphinxclient; use yiidbquery; use yiiwidgetslinkpager; use backendmodelsgoods; class soucontroller extends controller { //显示搜索页面 public function actionindex() { //接受搜索值 $sou=yii::$app->request->get('sou'); $p1=yii::$app->request->get('p1'); $p2=yii::$app->request->get('p2'); //echo $sou.$p1.$p2;die; //sphinx搜索 $cl = new sphinxclient(); $cl -> setserver('127.0.0.1',9312); $cl -> setconnecttimeout(3); $cl -> setarrayresult(true); if($sou) { //只搜索条件 $cl -> setmatchmode(sph_match_any); } else { //全局扫描 $cl -> setmatchmode(sph_match_fullscan); } //设置价格(注意:创建索引时,价格属性定义为int) if($p1&&$p2) { $cl->setfilterrange('price',$p1,$p2); } //搜索查询关键字 $res = $cl->query($sou,"mysql_goods"); //ajax分页 $model=new goods(); foreach ($res['matches'] as $key => $val) { $ids[] = $val['id']; } //查询条件数据 $query = $model->find()->where(['id'=>$ids]); $countquery = clone $query; $pages = new pagination(['totalcount' => $countquery->count(),'defaultpagesize'=>3]); //分页 $models = $query->offset($pages->offset) ->limit($pages->limit) ->all(); //关键字变红 foreach($models as $k=>$v) { $models[$k]['goods_name']=str_replace("$sou","<font color='red'>$sou</font>",$v['goods_name']);//将关键字替换成红色字体 } //显示列表,分配数据 return $this->render('index', [ 'res' => $models, 'pages' => $pages, 'sou'=>$sou, 'p1'=>$p1, 'p2'=>$p2 ]); } } ?>

视图层:

<?php use yiihelpershtml; use yiiwidgetsactiveform; use yiiwidgetslinkpager; $form = activeform::begin([ 'action' => 'index.php?r=sou/index', 'method' => 'get' ]) ?> <center> <div id="list"> 商品名称: <input type="text" name="sou" value="<?php echo $sou?>"> 价格区间: <input type="text" name="p1" value="<?php echo $p1?>">---<input type="text" name="p2" value="<?php echo $p2?>"> <input type="submit" value="搜索"> <table border="1" style="width:500px;"> <tr> <th>id</th> <th>商品名称</th> <th>商品价格</th> </tr> <?php foreach($res as $key=>$v){?> <tr> <td><?php echo $v['id'];?></td> <td><?php echo $v['goods_name'];?></td> <td><?php echo $v['price'];?></td> </tr> <?php }?> </table> <!--分页--> <?= linkpager::widget(['pagination' => $pages]) ?> </div> </center> <?php activeform::end() ?> <!--显示--> <?php $this->beginblock('test2') ?> $(document).on('click', '.pagination a', function(e) { //阻止page显示,看地址 e.preventdefault(); var href = $(this).attr('href'); $.post(href,function(msg){ $('#list').html(msg); }) }); <?php $this->endblock(); $this->registerjs($this->blocks['test2'] , yiiwebview::pos_end) ?>

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于yii框架的php程序设计有所帮助。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!