我有一个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?
答案 0 :(得分:4)
您可以在按钮 data 中发送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);
});
答案 1 :(得分: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作为单个变量。