Cakephp ajax 使用 j 查询删除

发布于 2025-01-07 05:55:25 字数 5865 浏览 1 评论 0原文

我发现了这个 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 都非常陌生。

是什么导致了这种行为? (此外,如果我尝试从控制器中删除重设,我会收到一条消息“未找到视图删除”)

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.

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

// 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.

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" )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

信愁 2025-01-14 05:55:25

首先检查食谱 HtmlHelper::链接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"
希望它能进一步帮助您;)

First of all check cookbook for HtmlHelper::link and JsHelper::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.
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(); but in your view is element with id="ajax_loader", so the selector should be $('#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;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文