在cakephp中更新数据库后的Ajax刷新表?

时间:2016-12-12 06:27:49

标签: ajax cakephp

如何在控制器中调用提交数据库的ajax之后刷新这样的表的内容。我用cakephp。

<table id="example" class="table">
<thead>
    <tr class="headings">
        <th>ID &nbsp;&nbsp;&nbsp;</th>
        <th>first name </th>
        <th>last name </th>
        <th>E-mail </th>
        <th>birthday </th>
    </tr>
</thead>

<tbody>
    <?php // empty for now ?>
</tbody>

我的ajax:

(function($) {
   $.fn.ApplyTask = function() {
       var task_id = $(this).data('task');
       var user_id = $(this).data('user');

       $.ajax({
           url: 'applyTask',
           cache: false,
           type: 'POST',
           data: {
               task_id: task_id,
               user_id: user_id
           },
           success: function(data) {

               }
           });
       };
   })($);

函数applyTask仅更新数据库的值。

public function applyTask() {
    if ($this->request->is('ajax') && !empty($this->request->data)) {
        $task_id = $this->request->data['task_id'];
        $user_id = $this->request->data['user_id'];

        if (!$this->TasksUser->findByTaskIdAndUserId($task_id, $user_id)) {
            throw new NotFoundException(__('Invalid tasks_users.'));
        }

        $this->TasksUser->updateAll(array('is_apply' => TRUE), array('task_id' => $task_id, 'user_id' => $user_id));
    } else {
        throw new MethodNotAllowedException('This method is now allowed.');
    }
}

1 个答案:

答案 0 :(得分:1)

在applyTask.ctp文件中,仅在tr

中获取数据

示例:

<?php foreach ($data as $data): ?>
       <tr>
              <td><?= h($data->id) ?></td>
              <td><?= $data->username ?></td>
        </tr>
<?php endforeach; ?>

然后在tbody添加ID或类,示例

<tbody id="fetch-data">
    <?php // empty for now ?>
</tbody>

现在在回调中只需通过以下代码添加数据

success: function(data) {
    $('#fetch-data').html(data);
}

注意:不要忘记在$this->viewBuilder()->layout(false);方法中使用applyTask