PHP 和 jQuery 之间的通信问题


Communication issue between PHP and jQuery

>我有一个从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?

您可以在按钮数据中发送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);
});

我通常会做这样的事情:

<?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作为单个变量。