(cakephp2.4.2)
CakePHP公式ブログチュートリアルに、ドットインストールの削除処理をAjax化を組み込んでみる
Controller
PostsCOntroller.php
public function delete($id) { if ($this->request->is('get')) { throw new MethodNotAllowedException(); } /* if ($this->Post->delete($id)) { */ /* $this->Session->setFlash(__('The post with id: %s has been deleted.', h($id))); */ /* return $this->redirect(array('action' => 'index')); */ /* } */ if ($this->request->is('ajax')) { if ($this->Post->delete($id)) { $this->autoRender = false; $this->autoLayout = false; $response = array('id' => $id); $this->header('Content-Type: application/json'); echo json_encode($response); exit(); } } $this->redirect(array('action' => 'index')); }
View
index.ctp
<?php foreach ($posts as $post): ?> <tr id="post_<?php echo h($post['Post']['id']); ?>"> <!-- ここ追加 --> <td><?php echo $post['Post']['id']; ?></td> <td> <?php echo $this->Html->link($post['Post']['title'], array('action' => 'view', $post['Post']['id']));?> </td> <td> <?php echo $this->Html->link('Delete', '#', array('class' => 'delete', 'data-post-id' => $post['Post']['id'])); ?> <!-- ここ追加 --> <?php echo $this->Html->link('Edit', array('action' => 'edit', $post['Post']['id'])); ?> </td> <td> <?php echo $post['Post']['created']; ?> </td> </tr> <?php endforeach; ?> <!-- スクリプト追加 --> <script> $(function() { $('a.delete').click(function(e) { if (confirm('Are you sure?')) { $.post('/posts/delete/' + $(this).data('post-id'), {}, function(res) { $('#post_' + res.id).fadeOut(); }, "json"); } return false; }); }); </script> </table>