php中的jquery ajax post数据只在第一次起作用
我试图在PHP中使用jQueryAjax删除数据。我可以第一次删除数据,但第二次就不行了。它只在我第一次刷新页面后才起作用。我检查了ajax的HTML响应,以确保没有任何错误,但它仍然不起作用。这是我的密码 index.phpphp中的jquery ajax post数据只在第一次起作用,php,jquery,ajax,Php,Jquery,Ajax,我试图在PHP中使用jQueryAjax删除数据。我可以第一次删除数据,但第二次就不行了。它只在我第一次刷新页面后才起作用。我检查了ajax的HTML响应,以确保没有任何错误,但它仍然不起作用。这是我的密码 index.php <div class="container"> <br> <button class="btn btn-primary" data-toggle="modal" data-target="#insert"&g
<div class="container">
<br>
<button class="btn btn-primary" data-toggle="modal" data-target="#insert">Thêm sinh viên</button>
<h1 align="center">Bảng sinh viên</h1>
<table class="table">
<thead>
<tr>
<th scope="col">Mã SV</th>
<th scope="col">Tên</th>
<th scope="col">SĐT</th>
<th scope="col">Giới tính</th>
<th scope="col">Hành động</th>
</tr>
</thead>
<tbody id="list">
<?php include('show.php') ?>
</tbody>
</table>
</div>
delete.php
require_once('db.php');
$real_id = $_POST['id'];
$sql = "DELETE FROM students WHERE real_id = ?";
//DELETE FROM table_name WHERE condition;
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$real_id);
$stmt->execute();
include("show.php");
show.php
$data ="";
while($row = $result->fetch_assoc()){
$data .="<tr>";
$data .= "<td>".$row['id']."</td>";
$data .= "<td>".$row['name']."</td>";
$data .= "<td>".$row['phone']."</td>";
switch ($row['sex']) {
case "1":
$sex = "Nam";
break;
case "2":
$sex = "Nữ";
break;
case "3":
$sex = "Khác";
break;
}
$data .= "<td>".$sex."</td>";
$realid = $row['real_id'];
$data .= "<td><button class='btn btn-danger delete' data-id='$realid'>Xoá</button></td>";
$data .="</tr>";
}
echo($data);
...
$data .= "<td><button class='btn btn-danger delete' onclick='deleteRecord('$realid')'>Xoá</button></td>";
...
$data=”“;
而($row=$result->fetch_assoc()){
$data.=“”;
$data.=''.$row['id'.'';
$data.=''.$row['name'].'';
$data.=''.$row['phone'].'';
开关($row['sex'])){
案例“1”:
$sex=“Nam”;
打破
案例“2”:
$sex=“Nữ";
打破
案例“3”:
$sex=“Khác”;
打破
}
$data.=''.$sex.'';
$realid=$row['real_id'];
$data.=“Xoá”;
$data.=“”;
}
回波(数据);
将Jquery编辑为:
$(document).on('click', 'button.delete',function(){ //<-----
var id = $(this).data('id');
var result = confirm("Bạn có muốn xoá sinh viên này không ?");
if(result){
$.ajax({
type: "POST",
url:"delete.php",
data: {'id':id},
success: function(response){
alert("Xoá thành công");
document.getElementById("list").innerHTML= response;
}
})
}
return false;
});
希望它能有所帮助。因为您正在动态地向数据添加按钮元素
$(".delete").on('click',function() {
// ..... this will not work second time.
}
试试下面的方法
$(document).on('click', '.delete' function(){
// This should work.
});
你能解释一下为什么我的代码没有运行以及你修复它的方式吗?非常感谢。因为在Ajax中你删除了最初加载的DOM元素,所以要在新元素上呈现click事件,你必须重新组织处理元素的方式,而不必重新加载。
$(".delete").on('click',function() {
// ..... this will not work second time.
}
$(document).on('click', '.delete' function(){
// This should work.
});