带有Ajax的DataTable无法正常工作

带有Ajax的DataTable无法正常工作

本文介绍了使用serverAide后,带有Ajax的DataTable无法正常工作:true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用DataTables的用户表,该表将包含200多个行.当我默认使用DataTables "pageLength": 10时,它看起来很好,这是表示例.

I have an user table using DataTables, that will contain more than 200 rows. It's look so fine when I'm using DataTables for default the "pageLength": 10, and this is the table example.

  Username     |   Type    |    Request   |
user01               1         request01
user02               1         request02
user03               2         request03
user04               1         request04
user05               1         request05
user06               1         request06
user07               1         request07
user08               1         request08
user09               1         request09
user10               1         request10

Showing 1 to 10 of 200 entries

Showing 1 to 10 of 200 entries

因此,为了减少加载时间,我决定使用"processing": true"serverSide": true.然后我遇到了这个"serverSide" : true的问题,它在表中打印了200行数据.

So, for reducing the loading time, I decide to use "processing": true and "serverSide": true. Then I got some issue with this "serverSide" : true, It's print 200 rows of data in table.

Showing 0 to 0 of 0 entries (filtered from NaN total entries).然后分页仍会打印,当我单击页面后,它什么也没做.

Showing 0 to 0 of 0 entries (filtered from NaN total entries). Then the pagination is still print and after I click the page , it's doing nothing.

我不希望DataTables首先获得10个数据,在单击分页后,它将再获得10个数据,依此类推.

I wan't the DataTables is getting the 10 data for the first, after pagination is clicked, it will get 10 more and so on.

我正在使用CodeIgniter,这是我的代码:

I'm using CodeIgniter, here is my code :

在我的视图+ Js 上:

<select name="task" id="task">
   <option value="1">Task 1</option>
   <option value="2">Task 2</option>
</select>
<table id="user-request" class="table">
<thead>
   <tr>
      <th>Username</th>
      <th>Type</th>
      <th>Request</th>
   </tr>
</thead>
</table>
<script>
... on task change ...
... var task = $("#task").val(); ...
   $('#user-request').DataTable({
        'processing': true,
        'serverSide': true,
        'ajax': {
            'type': 'POST',
            'url': base_url+'user/get_user_request',
            'data': {"task":task,"csrf_token":$("input[name=csrf_token]").val()}
        }
    })
</script>

注意:任务是另一个组,例如1类或2类,乌节大学或哈佛大学

Note : Task is a different group, example like Class 1 or Class 2, Orchard University or Harvard University

在我的控制器上:

$task = $this->input->post('task', TRUE);
$user_request = $this->model->all_user_request(task);
foreach ($user_request as $ur)
{
    $arr = array();
    $arr[] = $ur->username;
    $arr[] = $ur->type;
    $arr[] = $ur->request;
    $data[] = $arr;
}
$output = array(
    "data" => $data
);
if (COUNT($output) > 0)
{
    echo json_encode($output);
}

在我的模型上:

public function all_user_request($task_id) {
   $query = "SELECT * FROM user_request WHERE task_id = ?";
   return $this->db->query($query, $task_id)->result();
}

注意:在模型中实际使用的是2 INNER JOIN,我只是在这里简化了仅用于询问的选择. (仅在此处进入非规范化表).

Note : In model is actually using 2 INNER JOIN, I'm just simplifying the select only for asking here. (turning into denormalization table only in here).

我试图仅使用数字数据在控制器中将drawrecordsTotalrecordsFiltered添加到$output.例子

I was trying to add draw, recordsTotal, recordsFiltered to $output in my controller just using numeric data. Example

$output = array(
    "draw" => 5,
    "recordsTotal" => 5,
    "recordsFiltered" => 5,
    "data" => $data
);
if (COUNT($output) > 0)
{
    echo json_encode($output);
}

我一直在寻找答案,但我认为问题出在这里,但我仍然不知道必须从哪里获取draw-recordsTotal-recordsFiltered数据.我从其他人的另一个答案中看到,他们使用"draw" => $_POST['draw'],然后我尝试了此操作,但是却无济于事.

I was searching for the answer but, and I think the problem is here but I still have no idea where I must get the draw - recordsTotal - recordsFiltered data. I see on another answer from others, they use "draw" => $_POST['draw'], then I tried it, and it's do nothing.

因此,我尝试使用数字数据,但结果仍然相同.我需要一些帮助.它仍然在表中打印200行数据.

So I'm trying that using numeric data, but the result is still same. I need some help with this. It's still print 200 rows of data in table.

Showing 0 to 0 of 0 entries (filtered from NaN total entries).然后分页仍会打印,当我单击页面后,它什么也没做.

Showing 0 to 0 of 0 entries (filtered from NaN total entries). Then the pagination is still print and after I click the page , it's doing nothing.

推荐答案

数据表发送您需要的所有内容-如果您在网络下的控制台中查看,就会发现它们使用ajax-get方法发送这些请求到服务器

Datatables send everything you need - if you take a look in your console under network you'll see, that they use the ajax-get method to send those requests to the server

GET参数如下

draw
columns
start
length
search

这意味着-您必须正确调整模型...

which means - you've to adapt your model properly...

类似的东西应该起作用

public function all_user_request($task_id)
{
    $intStart = intval($this->input->get("start"));
    $intLength = intval($this->input->get("length"));
    $strSearch = (strlen($this->input->get("search")["value"]) >= 2) ?   $this->input->get("search",true)["value"]    :   false;
    $order = $this->input->get("order",true);


    $this->setQuery($task_id,$strSearch);

    $query = $this->db->get();
    $this->recordsTotal = $query->num_rows();

    $this->setQuery($task_id, $strSearch);

    if ($intStart >= 0 && $intLength > 0)
    {
        $this->db->limit($intLength,$intStart);
    }

    $strOrderField = 'username';
    $strDirection = "ASC";
    if (is_array($order))
    {
        switch($order[0]['column'])
        {
            case 1:
                $strOrderField = 'type';
                break;
            case 2:
                $strOrderField = 'request';
                break;

        }
        if (!empty($order[0]['dir']))    $strDirection = $order[0]['dir'];
    }
    $this->db->order_by($strOrderField,$strDirection);


    $query = $this->db->get();

    $arrData = $query->result();

    return $arrData;

}

public function getRecordsTotal()
{
    return $this->recordsTotal;
}

private function setQuery($task_id, $strSearch="")
{
    $this->db
        ->select('*')
        ->from('user_request')
        ->where('task_id', $task_id);

    if (!empty($strSearch))
    {
        $this->db->like('task_id', $strSearch);
    }

}

和您的控制器

//controller
$task = $this->input->post('task', TRUE);
$user_request = $this->model->all_user_request($task);

$data = [];
foreach ($user_request as $ur)
{
    $data[] = [
        $ur->username,
        $ur->type,
        $ur->request
    ];
}

$arrCompiledData = [
    'data' => $data,
    'draw' => $this->input->get('draw'),
    'recordsTotal' => $this->model->getRecordsTotal(),
    'recordsFiltered' => $this->model->getRecordsTotal(),
];

$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode($arrCompiledData));

请记住,我刚刚写下来-也许有一些错别字,但是您应该能够理解服务器端对数据表请求的处理应如何工作.

Please keep in mind i just wrote this down - maybe there are some typos, but you should be able to understand how the serverside processing of a datatables request should work.

这篇关于使用serverAide后,带有Ajax的DataTable无法正常工作:true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 14:42