我在网上发现了这个http://www.jamesfairhurst.co.uk/posts/view/ajax_delete_with_cakephp_and_jquery/教程,但它是针对cakephp 1.3的。
在做了一些调整之后,我尝试运行它,但出了点问题。当记录被删除(应该是)时,它刷新了页面。就像Ajax和Jquery一样。 以下是我的代码
控制器动作
function delete($id=null) {
// set default class & message for setFlash
$class = 'flash_failure';
$msg = 'Invalid User Id';
// check id is valid
if($id!=null && is_numeric($id)) {
// get the Item
$item = $this->User->read(null,$id);
// check Item is valid
if(!empty($item)) {
$user = $this->Session->read('Auth.User');
// $exists=$this->User->find('count',array('conditions'=>array("User.username" => $user)));
if($item['User']['username']==$user['username']){
$msg = 'You cannot delete yourself!';
}
// try deleting the item
else if($this->User->delete($id)) {
$class = 'flash_success';
$msg = 'User was successfully deleted';
} else {
$msg = 'There was a problem deleting User, please try again';
}
}
}
// output JSON on AJAX request
if(/*$this->RequestHandler->isAjax()*/$this->request->is('ajax')) {
$this->autoRender = $this->layout = false;
echo json_encode(array('success'=>($class=='flash_failure') ? FALSE : TRUE,'msg'=>"<p id='flashMessage' class='{$class}'>{$msg}</p>"));
exit;
}
// set flash message & redirect
$this->Session->setFlash($msg,$class,array('class'=>$class));
$this->redirect(array('action'=>'manage'));
}
视图
<?php //view/users/manage.ctp ?>
<h1 class="ico_mug">Users</h1>
<?php echo 'Add User '.$this->Html->link($this->Html->image("add.jpg"), array('action' => 'register'), array('escape' => false));//print_r ($users); ?>
</br>
<table id="table">
<tr>
<th>ID</th>
<th>Username</th>
<th>Last Login</th>
<th>Options</th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($users as $rs): ?>
<tr>
<?php echo $this->Html->script('jquery'); ?>
<td class="record">
<?php echo $rs['User']['id']; ?>
</td>
<td class="record"><?php echo $rs['User']['username']; ?></td>
<td class="record"><?php if(!$rs['User']['last_login']) {echo "Never Logged In";} else {echo $rs['User']['last_login'];} ?></td>
<td class="record"> <?php echo $this->Html->link($this->Html->image("edit.jpg"), array('action' => 'edit',$rs['User']['id']), array('escape' => false));?>
<?php
$user = $this->Session->read('Auth.User');
if($rs['User']['username']!=$user['username'])
echo $this->Html->link($this->Html->image("cancel.jpg"), array('action' => 'delete',$rs['User']['id']), array('escape' => false),array('class'=>'confirm_delete'));?>
<?php
if($rs['User']['username']!=$user['username'])
// simple HTML link with a class of 'confirm_delete'
echo $this->Js->link('Delete',array('action'=>'delete',$rs['User']['id']),array('escape' => false),array('class'=>'confirm_delete'));
?></td>
</tr>
<?php endforeach; ?>
<div class="paging">
<?php echo $this->Paginator->prev('<< ' . __('previous'), array(), null, array('class'=>'disabled'));?>
| <?php echo $this->Paginator->numbers();?>
| <?php echo $this->Paginator->next(__('next') . ' >>', array(), null, array('class' => 'disabled'));?>
</div>
</table>
<div id='ajax_loader'></div>
Jquery
// on dom ready
$(document).ready(function(){
// class exists
if($('.confirm_delete').length) {
// add click handler
$('.confirm_delete').click(function(){
// ask for confirmation
var result = confirm('Are you sure you want to delete this?');
// show loading image
$('.ajax_loader').show();
$('#flashMessage').fadeOut();
// get parent row
var row = $(this).parents('tr');
// do ajax request
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
// hide loading image
$('.ajax_loader').hide();
// hide table row on success
if(response.success == true) {
row.fadeOut();
}
// show respsonse message
if( response.msg ) {
$('#ajax_msg').html( response.msg ).show();
} else {
$('#ajax_msg').html( "<p id='flashMessage' class='flash_bad'>An unexpected error has occured, please refresh and try again</p>" ).show();
}
}
});
}
return false;
});
}
});
请记住,我对所有这些Jquery和Ajax以及cakephp都很新。
导致这种行为的原因是什么? (如果我尝试从控制器中删除重定向,我会收到一条消息“未找到视图删除”)
答案 0 :(得分:1)
首先查看HtmlHelper::link和JsHelper::link的食谱。不知道你有什么版本的蛋糕,所以只需切换到正确的蛋糕。
问题是 - 你的Delete
链接都没有类confirm_delete
(使用firebug或一些调试工具) - 所以链接被点击但javascript永远不会被执行,这就是你被重定向的原因。
在你的情况下,它将是:
echo $this->Html->link($this->Html->image('cancel.png'), array('controller' => 'users', 'action' => 'delete', $rs['User']['id']), array('escape'=>false, 'class'=>'confirm_delete') );
和
echo $this->Js->link('Delete', array('controller' => 'users', 'action'=>'delete', $rs['User']['id']), array('escape' => false, 'class'=>'confirm_delete'));
然后我看到$('.ajax_loader').hide();
,但在您的视图中是id="ajax_loader"
的元素,因此选择器应为$('#ajax_loader').hide();
与$('#ajax_msg').html(
相同,请仔细检查页面上是否包含id="ajax_msg"
的元素
希望它能进一步帮助你;)