简体   繁体   English

PHP和jQuery之间的通讯问题

[英]Communication issue between PHP and jQuery

I have a page generated from PHP like this: 我有一个从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>';
    }
?>

Then, in front side I have this script: 然后,在前端有以下脚本:

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

My aim is to make Delete button perform an ajax call to delete the user. 我的目的是使Delete按钮执行ajax调用以删除用户。 Till now I didn't got there yet, my problem is how to get the user ID? 直到现在我还没到那儿,我的问题是如何获取用户ID?

You can send the id within the button data and easily get it after. 您可以在按钮数据中发送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);
});

I usually do something like this: 我通常会这样:

<?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>';
    }
?>

And then in jQuery 然后在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;
    });
});

I haven't tested the code but it should work. 我还没有测试代码,但是应该可以。 Have in mind that there are loads of ways to do this and this is my preferred way. 请记住,有很多方法可以做到这一点,这是我的首选方法。 My point is that you don't necessarily need the id as an individual variable. 我的观点是,您不一定需要将id作为单个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM