当使用JQuery追加生成表时,通过AJAX删除记录

时间:2016-11-04 15:25:06

标签: javascript php jquery ajax

我有一个包含数据的html表。我想通过ajax删除记录,但我有点挣扎,因为我的表是用append生成的:

        ...
        $.each(data, function(id, won) {
                                if (data[i].flag == 0)   {flag='<img src="../images/flag-y.png"  width="20" height="20">'} else {flag='<img src="../images/flag.png"  width="20" height="20">'}

                             $el.append('<tr><td>'+data[i].id+'</td>
    <td><a href="?identifier='+data[i].id+'&token='+data[i].token+'"><img src="../images/edit.png"  width="20" height="20"></a></td>
 <td><a href="?delete='+data[i].id+'&deletetoken='+data[i].token+'"><img src="../images/delete.png"  width="20" height="20" class="delete"></td> </tr>');
                              i = ++ i;                                                                                       
                            } );
        ...

有效。但如果有人点击上一栏的图片(我不需要php文件的帮助),如何将参数传递给ajax调用?

$('a.delete').click(function(e) {
        e.preventDefault();

     var parent = $(this).parent();
        $.ajax({
            type: 'get',
            url: 'jquery-record-delete.php',
            data: 'ajax=?delete,
            beforeSend: function() {
                parent.animate({'backgroundColor':'#fb6c6c'},300);
            },
            success: function() {
                parent.slideUp(300,function() {
                    parent.remove();
                });
            }
        });

    });

我需要传递delete和deletetoken变量。

1 个答案:

答案 0 :(得分:1)

我建议您为每个data-id添加<tr>属性,如下所示:

$el.append('<tr data-id="+ data[i].id +" data-token="+ data[i].token +">
    + '<td>' + data[i].id + '</td>'
    + '<td>'
        + '<a href="?identifier=' + data[i].id + '&token=' + data[i].token + '">'
            + '<img src="../images/edit.png"  width="20" height="20">'
        + '</a>'
    + '</td>'
    + '<td>'
        + '<a href="?delete=' + data[i].id + '&deletetoken=' + data[i].token + '" class="delete">' // also, you listen to a.delete click, so let's add "delete" class to it
        + '<img src="../images/delete.png" width="20" height="20" class="delete">'
        + '</a>' // I think you were missing closing a tag here
    + '</td>'
+ '</tr>');
i++;

因此您可以在侦听器回调中轻松抓取它:

$('body').on('click', 'a.delete', function(e) {
    e.preventDefault();

    var tr = $(this).closest('tr'),
        token = tr.data('token'),
        id = tr.data('id'); // we have the ID
    $.ajax({
        type: 'get',
        url: 'jquery-record-delete.php',
        data: {
            id: id, // passing id,
            token: token,
            ajax: 'delete'
        },
        beforeSend: function() {
            tr.animate({'backgroundColor':'#fb6c6c'},300);
        },
        success: function() {
            tr.slideUp(300,function() {
                tr.remove();
            });
        }
    });
});