【问题标题】:Ajax refresh table after database updated in cakephp?在cakephp中更新数据库后Ajax刷新表?
【发布时间】:2016-12-12 06:27:49
【问题描述】:

在控制器中调用 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.');
    }
}

【问题讨论】:

  • 你的 php 代码如何返回对 ajax 调用的响应?

标签: ajax cakephp


【解决方案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);
}

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

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2018-06-20
    • 2021-10-11
    相关资源
    最近更新 更多