javascript 使用按钮删除sql行而不刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26468089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete sql row using button without refreshing page
提问by Erin H
I want to delete a row from table with delete button with confirmation from user but without page refreshing with help of jQuery ajax.
我想通过用户确认删除带有删除按钮的表中的一行,但没有在 jQuery ajax 的帮助下刷新页面。
I know a little about php, html, javascript, jquery, and sql. I dont know how to go about doing this but what i really want to do is to be able to pull data from a sql table (i already know how to do this).
我对 php、html、javascript、jquery 和 sql 略知一二。我不知道如何去做,但我真正想做的是能够从 sql 表中提取数据(我已经知道如何做到这一点)。
Then display the data with a button next to it (i also already know how to do). When they click the button it will remove the element that hold the visible data and also send a sql statment to delete the row in the database. A very crude code over view.
然后用旁边的按钮显示数据(我也已经知道该怎么做)。当他们单击按钮时,它将删除保存可见数据的元素,并发送一个 sql 语句来删除数据库中的行。一个非常粗略的代码概览。
<?php
echo '<p>Data 1: '".$someDataFromDB."'<button id='deleteThisRow'></button></p>;
?>
from this I would like to:
由此我想:
- Click the button
- remove the paragraph element so they users know it was deleted
- then send an sql statement to delete the row from the sql table
- 点击按钮
- 删除段落元素,以便他们的用户知道它已被删除
- 然后发送一条sql语句从sql表中删除该行
All this without refreshing the page. Is that at all possible?
所有这些都无需刷新页面。这可能吗?
回答by Clinton Dsouza
Yes it is possible but you should only send the id of the entry to a particular page to delete the entry.never the entire sql statement.
是的,这是可能的,但您应该只将条目的 id 发送到特定页面以删除条目。永远不要删除整个 sql 语句。
<button id="<?php echo $row['id']; ?>" class="delbutton"></button>
add this script to your page
将此脚本添加到您的页面
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data : info,
success : function() {
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
</script>
and last but no the least your delete script
最后但并非最不重要的是你的删除脚本
<?php
include 'connection.php';
$id=$_POST['id'];
$delete = "DELETE FROM table WHERE id=$id";
$result = mysql_query($delete) or die(mysql_error());
?>