1

我有一个从 PHP 生成的页面,如下所示:

<?php
    //In my original code, this is retrieved from databas..
    $users = array(
        array('id'=>1, 'login'=>'login1', 'email'=>'email1')
    );  
    foreach($users as $user){
        echo '<tr><td>'.$user['login'].'</td><td>'.$user['email'].'</td><td><button class="button-delete">Delete</button></td></tr>';
    }
?>

然后,在前面我有这个脚本:

$('.button-delete').click(function(){
    var id=0;
    alert(id);
});

我的目标是让删除按钮执行 ajax 调用来删除用户。直到现在我还没有到那里,我的问题是如何获取用户 ID?

4

2 回答 2

4

您可以在按钮数据中发送 id并在之后轻松获取它。

<?php
    //In my original code, this is retrieved from databas..
    $users = array(
        array('id'=>1, 'login'=>'login1', 'email'=>'email1')
    );  
    foreach($users as $user){
        echo '<tr><td>'.$user['login'].'</td><td>'.$user['email'].'</td><td><button class="button-delete" data-id="'.$user['id'].'">Delete</button></td></tr>';
    }
?>

$('.button-delete').click(function(){
    var id=$(this).data('id');
    alert(id);
});
于 2012-06-07T10:12:16.767 回答
1

我通常会这样做:

<?php
    //note the change from button tag to anchor tag
    $users = array(
        array('id'=>1, 'login'=>'login1', 'email'=>'email1')
    );  
    foreach($users as $user){
        echo '<tr><td>'.$user['login'].'</td><td>'.$user['email'].'</td><td><a href="/link/to/delete/id/'.$user['id'].'/" class="button-delete">Delete</a></td></tr>';
    }
?>

然后在 jQuery 中

$(document).ready(function(){
    $('.button-delete').click(function(){
        var $this = $(this);
        //Make an AJAX request to the delete script using the href attribute as url
        $.get($this.attr('href'), function(response) {
            //Inside your php script echo out 1 if the delete was successful.
            if(response) {
                //remove the parent row
                $this.parents('tr').fadeOut(1000, function(){
                    $(this).remove();
                });
            }
        });
        return false;
    });
});

我还没有测试过代码,但它应该可以工作。请记住,有很多方法可以做到这一点,这是我的首选方式。我的观点是,您不一定需要将 id 作为单个变量。

于 2012-06-07T10:21:40.240 回答