簡體   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