效果
说明
基于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');
//这里我做的一个模糊查询到名字或者对应的id,主要目的因为我这个系统是
//商城系统里面用到直接看产品ID
$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;
}
}
?>
功能实现中注意点
- Uncaught TypeError: Cannot use ‘in’ operator to search for ” in JSON string
- $.each(JSON.parse(data)或$.each($.parseJSON(data)来解决
- 大多数web应用程序将直接返回JSON格式化的字符串,你需要把它转换成JavaScript对象能够解析的格式。
- 这里用的是essyui-comboBox的loader方法触发ajax的异步请求,然后将获取后台数据写到下拉框中,注意的是写入的是t_goods表的spec字段的值。
[{"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","code":"1002","model":"80\u514b","purchase_price":"0.10","py":null,{"id":"3","code":"1003","spec":"A3","sale_price":"0.30","purchase_price":"0.15",{"id":"4","code":"1004","sale_price":"0.40","purchase_price":"0.20",{"id":"5","category_id":"102","code":"1005","name":"DoubleA",{"id":"6","code":"1006",{"id":"7","code":"1007","bar_code":null}]