gpt4 book ai didi

javascript - 删除 div 内的一行

转载 作者:行者123 更新时间:2023-11-29 11:41:56 24 4
gpt4 key购买 nike

我想在每个 div 中插入一个“删除”按钮,以便可以使用删除按钮删除数据库行和 div。 p>

div 的数量根据数据库中的行数而变化。

It should appear as follows,

显示数据效果很好。但是,删除(删除按钮)不起作用。

PHP

    function deleteUser($connection, $userID){  //  this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";

if (mysqli_query($connection, $sql2)) {
header("Location: main.php");

} else {
echo "Error! ";
}

}


function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);

if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];

echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';

if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}

mysqli_close($connection);
}

currentUsers($connection);


?>

最佳答案

根据评论的讨论,给出了以下代码。

更新的 HTML:

<input type="button" name="removeButton" value="Remove" class="removeBtn">

Javascript:

var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});

page.php

//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}

If you want to remove the total div as well with the database field then use:

Javascript:

var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});

If you want to pass your $userID in each input then use:

<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">

Javascript

$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});

这只是您问题的答案,但您必须根据需要使用它。这可能对您有帮助,请尝试让我知道发生了什么。

关于javascript - 删除 div 内的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35633767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com