基于thinkphp3.2.3版本的框架实现,利用ajax从后台数据库中获取数据,其中获取数据是用模糊搜索方式,返回json数据,然后在模板中利用js将数据显示到搜索框下拉面板中。
<script> var myloader = function(param,success,error){ var q = param.q || ''; if (q.length <= 0) { console.log("q.length <= 0"); return false; } else { console.log("q.length > 0"); } $.ajax({ url: '__CONTROLLER__/search/', type: 'POST', dataType: 'json', data: {'searchValue': q}, success: function(data){ var items = $.each(JSON.parse(data), function(value){ return value; }); success(items); } }); } </script>
<body>
<div>
<input class="easyui-combobox" data-options=" valueField:'code' , textField:'spec', loader : myloader, mode : 'remote'"/>
</div>
</body>
<?php
//---------------------------------------------------
//功 能:动态模糊搜索测试
//创建日期:2015-10-27
//修改日期:2015-10-27
//创 建 人:yicm
//修 改 人:yicm
//修改内容:
//---------------------------------------------------
namespace Home\Controller;
use Think\Controller;
class SearchController extends Controller {
public function index(){
$this->assign('title','动态模糊搜索测试');
$this->display();
}
public function helloSearch(){
echo 'hello search!';
}
public function search(){
$keyword = $_POST['searchValue'];
//$keyword = 'A4';
$Goods=M('t_goods');
//这里模糊查询到商品编码、名字和商品型号和规格
$map['code|name|spec|model'] = array('like','%'.$keyword.'%');
// 把查询条件传入查询方法
if($goods = $Goods->where($map)->select()){
$returnData = json_encode($goods);
$this->ajaxReturn($returnData);
}else{
$goods['content'] = 'failed';
$returnData = json_encode($goods);
$this->ajaxReturn($goods);
}
}
//获取商品记录数
function getCount(){
$credit = M('t_goods');
$count = $credit->count(); //计算记录数
echo $count;
}
}
?>
下面是ajax获取后台数据返回的一部分测试数据data:
[{"id":"1","category_id":"101","code":"1001","name":"\u6cf0\u683c\u98ce\u8303","spec":"A4","model":"70\u514b","unit_id":"\u5f20","sale_price":"0.20","purchase_price":"0.09","py":"tgff","bar_code":null},{"id":"2","category_id":"101","code":"1002","name":"\u6cf0\u683c\u98ce\u8303","spec":"A4","model":"80\u514b","unit_id":"\u5f20","sale_price":"0.20","purchase_price":"0.10","py":null,"bar_code":null},{"id":"3","category_id":"101","code":"1003","name":"\u6cf0\u683c\u98ce\u8303","spec":"A3","model":"70\u514b","unit_id":"\u5f20","sale_price":"0.30","purchase_price":"0.15","py":null,"bar_code":null},{"id":"4","category_id":"101","code":"1004","name":"\u6cf0\u683c\u98ce\u8303","spec":"A3","model":"80\u514b","unit_id":"\u5f20","sale_price":"0.40","purchase_price":"0.20","py":null,"bar_code":null},
{"id":"5","category_id":"102","code":"1005","name":"DoubleA","spec":"A4","model":"70\u514b","unit_id":"\u5f20","sale_price":"0.20","purchase_price":"0.09","py":null,"bar_code":null},{"id":"6","category_id":"102","code":"1006","name":"DoubleA","spec":"A4","model":"80\u514b","unit_id":"\u5f20","sale_price":"0.20","purchase_price":"0.10","py":null,"bar_code":null},{"id":"7","category_id":"102","code":"1007","name":"DoubleA","spec":"A3","model":"70\u514b","unit_id":"\u5f20","sale_price":"0.30","purchase_price":"0.15","py":null,"bar_code":null}]