繁体   English   中英

CakePHP AJAX删除与J查询

[英]Cakephp ajax delete with j query

我在网络上找到了该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都是新手。

是什么原因导致这种行为? (同样,如果我尝试从控制器中删除重做,则会收到一条消息“未找到视图删除”)

首先检查HtmlHelper :: linkJsHelper :: link的食谱。 不确定您使用的蛋糕是什么版本,因此只需切换到正确的蛋糕即可。 问题是-您的Delete链接都没有class 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"元素,希望它对您id="ajax_msg"帮助;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM