如何在javascript中编写php

S.A*_*ram -3 javascript php mysql

我用以下方式在JavaScript中编写php.即使删除功能工作,警报也没有到来.

这是我的代码:

Delete.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>
Run Code Online (Sandbox Code Playgroud)

geo*_*oot 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>
Run Code Online (Sandbox Code Playgroud)

而delete.php就像

<?php
//write code for delete here
?>
Run Code Online (Sandbox Code Playgroud)

另一点是标题("Location ...")将重定向但在ajax中,因此最好不要使用php重定向,但检查javascript然后使用document.location进行重定向.