简体   繁体   English

CakePHP AJAX删除与J查询

[英]Cakephp ajax delete with j query

i've found this http://www.jamesfairhurst.co.uk/posts/view/ajax_delete_with_cakephp_and_jquery/ tutorial on the web, but it was for cakephp 1.3. 我在网络上找到了该http://www.jamesfairhurst.co.uk/posts/view/ajax_delete_with_cakephp_and_jquery/教程,但这是针对cakephp 1.3的。

After making some adjustements to it , i try to run it, but something is going wrong. 对它进行一些调整后,我尝试运行它,但是出了点问题。 While the record gets deleted(as it should be), it refreshed the page. 在删除记录(应删除记录)的同时,刷新了页面。 It's like Ajax and Jquery are not working. 就像Ajax和Jquery无法正常工作一样。 Below is my code 下面是我的代码

The Controller Action 控制器动作

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'));
}

The View 风景

    <?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>

The Jquery 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;
    });
}
});

Please take in mind that i'm very new to all this Jquery and Ajax thing, as well as in cakephp. 请记住,我对这一切Jquery和Ajax以及Cakephp都是新手。

What is causing that behaviour ? 是什么原因导致这种行为? (also if i try to remove the redire from the controller, i get a message that "view delete was not found" ) (同样,如果我尝试从控制器中删除重做,则会收到一条消息“未找到视图删除”)

First of all check cookbook for HtmlHelper::link and JsHelper::link . 首先检查HtmlHelper :: linkJsHelper :: link的食谱。 Not sure what version of cake you have, so just switch to the right one. 不确定您使用的蛋糕是什么版本,因此只需切换到正确的蛋糕即可。 The thing is - none of your Delete links has class confirm_delete (use firebug or some debugging tool) - so the link gets clicked but the javascript is never executed, that's why you get redirected. 问题是-您的Delete链接都没有class confirm_delete类(使用firebug或某些调试工具)-因此,该链接被单击,但是javascript从不执行,这就是您被重定向的原因。 In your case it would be: 您的情况是:

echo $this->Html->link($this->Html->image('cancel.png'), array('controller' => 'users', 'action' => 'delete', $rs['User']['id']), array('escape'=>false, 'class'=>'confirm_delete') );

and

echo $this->Js->link('Delete', array('controller' => 'users', 'action'=>'delete', $rs['User']['id']), array('escape' => false, 'class'=>'confirm_delete'));

Then I see $('.ajax_loader').hide(); 然后我看到$('.ajax_loader').hide(); but in your view is element with id="ajax_loader" , so the selector should be $('#ajax_loader').hide(); 但是在您看来是id="ajax_loader"元素,所以选择器应该是$('#ajax_loader').hide(); Same with $('#ajax_msg').html( , double check you have that element on page with the id="ajax_msg" Hope it helps you further;) $('#ajax_msg').html( ,请仔细检查您的页面上是否有id="ajax_msg"元素,希望它对您id="ajax_msg"帮助;)

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

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