duanlong4890 2017-05-27 18:12
浏览 42
已采纳

使用ajax删除行并删除页面上的记录

I'm trying to remove the record in database via ajax. In the same time I want to delete also the record from the page. So I have this in my HTML

<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
    <li>
        <div class="comment-main-level">
            <div class="comment-box">
                <div class="comment-head">
                    <h6 class="comment-name by-author">'.$row['author'].''</h6>

                    <a href="?delete='.$row['id'].'" class="del">
                        <i class="fa fa-trash "></i>
                    </a>

                </div>
            </div>
        </div>
    </li>
</ul>

This is inside the loop which display all records on page. This is the ajax function

$(document).ready(function() {
    $('.del').click(function(e) {
        e.preventDefault();
        var parent = $(this).parent();
        $.ajax({
            type: 'get',
            url: 'delete.php',
            data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
            beforeSend: function() {
                parent.animate({'backgroundColor':'#fb6c6c'},300);
            },
            success: function() {
                parent.slideUp(300,function() {
                    parent.remove();
                });
            }
        });
    });
});

And my delete.php is simple delete query

$stmt = $pdo->prepare("DELETE FROM comment where id = :id"); 
$stmt->bindParam(':id', (int)$id, PDO::PARAM_INT);
$stmt->execute();

Current error is from the ajax when I click on delete on this line index.php:183 Uncaught TypeError: Cannot read property 'replace' of undefined

Uncaught TypeError: Cannot read property 'replace' of undefined

The ajax part is from tutorial since I'm very unfamiliar with js/ajax.

What can be the problem here?

  • 写回答

3条回答 默认 最新

  • douming4359 2017-05-27 18:30
    关注

    In your function $(this) = <a href="?delete='.$row['id'].'" class="del">.

    var parent = $(this).parent(); = <div class="comment-head"> which has no ID. Thus attr('id') returns undefined.

    You can select the ul element this way:

    var parent = $(this).closest('ul.comments-list.record');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器