我正在尝试删除一行数据库。记录正在删除,但问题是页面正在重新加载。因为,我正在使用AJAX,页面不应该刷新。 这是js函数:
function delThis(id)
{
var deleteRow = id;
var page = "stu_rec1.php";
var parameters ='deleteRow='+deleteRow;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert("Form sent successfully");
};
xmlhttp.open("POST",page,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}
以下是HTML代码:
<?php for($i=0;$i<count($id);$i++){?>
<tr>
<td><?php echo $name[$i];?></td>
<td><?php echo $email[$i];?></td>
<td><?php echo $mobno[$i];?></td>
<td><?php echo $gender[$i];?></td>
<td><?php echo $address[$i];?></td>
<td><input type="submit" name="delete" value="Delete" id="delete" onclick="delThis(<?php echo $id[$i];?>);" ></td>
</tr>
<?php }?>
这是执行删除的代码:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="myDB";
$delete = $_POST["deleteRow"];
$conn = new mysqli($servername, $username, $password,$db);
if ($conn->connect_error) {
die("Connection failed: ".mysqli_connect_error());
}
$sql = "SELECT name, email, mobileno,gender,address FROM studentrecords";
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($delete !="")
{
$query= "DELETE FROM studentrecords WHERE id='$delete'";
$result1 = mysqli_query($conn, $query);
}
mysqli_close($conn);
?>
答案 0 :(得分:1)
请更改type =&#34;提交&#34;输入=&#34;按钮&#34;
<?php for($i=0;$i<count($id);$i++){?>
<tr>
<td><?php echo $name[$i];?></td>
<td><?php echo $email[$i];?></td>
<td><?php echo $mobno[$i];?></td>
<td><?php echo $gender[$i];?></td>
<td><?php echo $address[$i];?></td>
<td><input type="button" name="delete" value="Delete" id="delete" onclick="delThis(<?php echo $id[$i];?>);" ></td>
</tr>
<?php }?>
function delThis(id)
{
var deleteRow = id;
var page = "stu_rec1.php";
var parameters ='deleteRow='+deleteRow;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert("Form sent successfully");
//add here your callback row remove code
};
xmlhttp.open("POST",page,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}