服务端后端完整代码
1)控制器代码:
public function index()
{
if(IS_AJAX){
$list = D('Msg')->getData(I('get.'));
$this->ajaxReturn($list);
}
$this->display();
}
2) Model层代码:(*其中,dealTime方法主要用于处理时间段)
public function getData($data)
{
//获取Datatables发送的参数 必要
$draw = $data['draw']; //这个值直接返回给前台
//获取时间区间
$timeArr['mintime'] = $data['mintime'];
$timeArr['maxtime'] = $data['maxtime'];
$where = $this->dealTime($timeArr);
//搜索框
$search = trim($data['search']['value']); //获取前台传过来的过滤条件
if(strlen($search) > 0) {
$where['id|fromnickname|content|msgtype'] = array('like','%'.$search.'%');
}
//定义查询数据总记录数sql
$recordsTotal = $this->count();
//定义过滤条件查询过滤后的记录数sql
$recordsFiltered = $this->where($where)->count();
//排序条件
$orderArr = [1=>'id', 2=>'fromnickname', 3=>'content', 4=>'msgtype', 5=>'time'];
//获取要排序的字段
$orderField = (empty($orderArr[$data['order']['0']['column']])) ? 'id' : $orderArr[$data['order']['0']['column']];
//需要空格,防止字符串连接在一块
$order = $orderField.' '.$data['order']['0']['dir'];
//按条件过滤找出记录
$result = [];
//备注:$data['start']起始条数 $data['length']查询长度
$result = $this->field('id,fromnickname,content,msgtype,time')
->where($where)
->order($order)
->limit(intval($data['start']), intval($data['length']))
->select();
//处理数据
if(!empty($result)) {
foreach ($result as $key => $value) {
$result[$key]['time'] = date("Y-m-d H:i:s",$value['time']);
$result[$key]['recordsFiltered'] = $recordsFiltered;
}
}
//拼接要返回的数据
$list = array(
"draw" => intval($draw),
"recordsTotal" => intval($recordsTotal),
"recordsFiltered"=>intval($recordsFiltered),
"data" => $result,
);
return $list;
}
3) 实现自定义ajax搜索
1. 在WdatePicker中添加onpicked回调函数
2. 执行table.fnFilter(),其中table为datatables对象
以WdatePicker插件为例(input框类似,绑定onchange事件即可):
<input type="text" onfocus="WdatePicker({maxDate:'#F{ $dp.$D(\'logmax\')||\'%y-%M-%d\'}', onpicked:function(){table.fnFilter();}})" name="mintime" id="logmin" class="input-text Wdate" style="width:120px;">
3. datatables中ajax属性中data属性定义额外要传递的参数
例子:
ajax: {
"url":"{:U('Msg/index')}",
"data":function(d){ //额外传递的参数
d.mintime = $('#logmin').val();
d.maxtime = $('#logmax').val();
}
4) 代码截图:
上一篇: PHP使用ActiveMQ实例
下一篇: PHP实现QQ登录的开原理和实现过程