使用Ajax和JQuery从SQL数据库中添加和删除一行


Adding and deleting a row from SQL database using Ajax and JQuery

我有一个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异步完成这项工作,也就是说,我不想刷新我的页面。尝试了无数种方法,但每次都失败了。提前谢谢。

您需要编写自己的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
      }
    });
}

另一种方式:首先,为每个删除按钮分配一个唯一的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}
    });
});