我目前正在使用 HTML、PHP、Javascript 和 AJAX 的组合来创建一个 HTML ,从 MySQL 数据库中的一个表中填充它,然后在表的内部添加一个以同时删除行, 并从 MySQL 数据库中删除该条目。这是我目前拥有的:
<?php
echo '<table id="tag_table" border=1>
<tr>
<th>Tags</th>
<th>Delete Tag</th>
</tr>';
$iter = 0;
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
echo "<tr id=" . $iter . "\">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>";
echo "<button id=\"delete\">Delete</button>";
echo "</td> </tr>";
}
?>
现在我想做的是向删除按钮添加 .click() 功能,但我卡住了,因为我想使用以下 Javascript 删除该行:
function deleteTag(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
但我还需要删除 MySQL 数据库中的相应条目,需要 PHP(我无法在 javascript 文件中使用)。如果有人对如何完成这些事情有可能的解决方案或想法,我将不胜感激。
感谢您的帮助。
编辑 1. 我的 PHP 代码:
<?php
$db = new PDO('my info here bla bla bla');
$query = "DELETE FROM Tags WHERE name=" . $_POST['name'];
$db->exec($query);
$db = null;
?>
最佳答案
您可以在按钮标签中结合使用 onclick=?
属性和 JS 函数:onclick=removeTag(this)
。
<?php
echo "
<table class="tag_table" border=1>
<tr>
<th>Tags</th>
<th>Delete Tag</th>
</tr>";
$iter = 0;
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row)
{
echo "<tr class=" . $iter . ">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>";
echo "<button onclick=\"deleteTag(this)\" class=\"delete\">Delete</button>";
echo "</td></tr>";
}
?>
JS:
function deleteTag(btn) {
// select the row that's concerned
var row = btn.parentNode.parentNode;
// select the name of this row
var name = row.children[0].textContent;
// remove the row on client side
row.parentNode.removeChild(row);
// AJAX call to remove the row server side
$.ajax({
url: 'removeRow.php', // this is the target PHP file
type: "GET",
data: ({
name: name
}),
success: function(data) {
// the following will be executed when the request has been completed
alert('Entry has been deleted successfully!');
}
});
}
PHP:诀窍是您需要使用 $_REQUEST['...']
不使用 $_GET[' 检索 AJAX 发送的变量...']
或 $_POST['...']
<?php
if($_REQUEST['name']) {
// if the variable has been successfully received
$name = $_REQUEST['name'];
$db = new PDO('my info here bla bla bla');
$query = $db->prepare("DELETE FROM Tags WHERE name = :name");
$query->execute(array('name' => $name));
unset($db, $query)
}
关于php - 如何使用 AJAX 从 MySQL 数据库中删除 HTML 行和删除条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905032/