我用以下方式在JavaScript中编写php。即使删除功能工作,警报也没有到来。
这是我的代码:
<script type="text/javascript">
function delete_id(id) {
if (confirm('Are you sure To Remove This Record ?')) {
<?php
include('database_connect.php');
if (isset($_GET['variable'])) {
$sql_query = "DELETE FROM register WHERE id=".$_GET['variable'];
mysqli_query($con, $sql_query);
header("Location: newusers.php");
}
mysqli_close($con);
?>
}
}
</script>
答案 0 :(得分:5)
你不能这样做。正确的方法是向后端发出ajax请求,然后让php删除该行。
修改强> 这里有一些示例代码
<script>
function delete_id() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert("deleted");
}
};
xhttp.open("GET", "/delete.php", true);
xhttp.send();
}
</script>
,delete.php就像
<?php
//write code for delete here
?>
另一点是标题(&#34;位置...&#34;)会重定向但是在ajax中,因此最好不要使用php重定向,但检查javascript然后使用document.location重定向。