我有一个PHP代码段,可以生成一个表并填充它,并在每行的末尾添加一个删除按钮。
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><form action='delete.php' method='post'><button type='submit' value=$num name='deleteId'>delete</button></form></td>";
echo "</tr>";
}
delete.php文件就是这个:
<?php
$host="localhost";
$username="root";
$password="";
$db_name="students";
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$id = $_POST['deleteId'];
$sql="DELETE FROM students WHERE id='$id'";
$result=mysql_query($sql);
?>
我想异步使用Ajax,即。我不希望我的页面刷新。尝试了一百万种方式,但每次都失败了。提前谢谢。
答案 0 :(得分:1)
您需要编写自己的JavaScript来处理服务器调用,而不是使用表单。这是一种方法。让你的PHP看起来像这样:
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button onclick="deleteStudent($num)">delete</button></td>";
echo "</tr>";
}
然后有一个看起来像这样的JS函数:
function deleteStudent(studentId) {
$.ajax({
url: "delete.php",
method: 'post',
data: {
deleteId: studentId
}
});
}
答案 1 :(得分:1)
另一种方式: 首先,为每个删除按钮分配一个唯一的ID。
while($row = mysql_fetch_array($result)){
$num = $row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button id='delete-" . $row['id'] . "'>delete</button></td>";
echo "</tr>";
}
然后使用jQuery:
$('button[id^="delete"]').click(function () {
var id = $(this).attr('id').substr(6);
$.ajax({
type: "POST",
url: "delete.php",
data: {deleteId: id}
});
});