PHP使用JS确认框时删除按钮?

时间:2011-08-03 17:17:40

标签: php javascript ajax

我在我的页面上运行了一个脚本,我想为每个结果添加一个删除按钮,但在它们能够删除之前我想要弹出一个javascript弹出窗口,询问他们是否确定要删除它。只是问一下最好的方法是什么? (我将使用 Ajax 运行删除功能,因为我不想在删除后离开页面。)

这是我正在使用的代码,到目前为止一切正常 - 结果显示,删除按钮弹出确认框。现在我被卡住了。

弹出:

<script type="text/javascript">
 window.show_confirm = function() {
var r = confirm("Are you sure you want to delete?");
if (r == true) {
    alert(" I NEED TO DO SOMETHING HERE? ");
} else {
    alert("The item won't be deleted.");
}
}
</script>

PHP while:

<?php 
while ($row_apps = mysql_fetch_array($result_apps))
{
    if ( ($row_apps['type'] == 'ar') && ($row_apps['client'] == NULL) ) {
echo '<center>
<div id="tab_listing">
<table width="248" border="0" cellspacing="10px" cellpadding="0px">
  <tr>
    <td width="100%" colspan="3"><div class="tab_listing_header">'.$row_apps['app_name'].'</div></td>
  </tr>
  <tr>
  <td class="tab_listing_values"><b>App ID: </b>'.$row_apps['app_id'].'</td>
    <td class="tab_listing_values"><b>Users: </b>'.$row_apps['users'].'</td>
  </tr>
</table>
<div id="edit">Edit</div>
<a href="#" onclick="return show_confirm()"><div id="delete"></div></a>
</div>
</center><br>';
} 
}
?>

如果有人可以提出一种方法来做那件事,请感激不尽:)

1 个答案:

答案 0 :(得分:1)

首先,你不应该在循环中使用相同的id!如果你有多个元素,请使用class!但是拥有一个id也很有用,所以将它绑定到输出的唯一元素:

<div id="_<?php echo $row_apps['app_id']; ?>" class="tab_listing">

为了引用您要删除的条目,您必须将类似ID的内容传递给delete-function,例如

<a href="#" onclick="return show_confirm(<?php echo $row_apps['app_id']; ?>)"><div id="delete"></div></a>

因此脚本必须如下所示:

<script>
 window.show_confirm = function(id) { //notice the passed in parameter
var r = confirm("Are you sure you want to delete?");
if (r == true) {
    alert(" I NEED TO DO SOMETHING HERE? ");
    //now do an ajax-request with the id you want to delete
    //after the request, do something with the div ('_'+id), 
    //e.g. hide or add a text.
    //with jQuery it's 1 line of code:
    // $.post('delete.php', {'id':id}, function(data){$('#_'+id).html('Deleted!')});
} else {
    alert("The item won't be deleted.");
}
}
</script>

对于AJAX的东西,我建议使用jQuery - 它会为你节省很多工作!

delete.php看起来像这样:

<?php

if(isset($_POST['id'])) {
  $id = $_POST['id'];
  //do something with the id...
}

?>