Calling a PHP Method from JavaScript [closed]

2019-09-22 12:43发布

问题:

I was under the impression that since JavaScript is client-side and PHP is server-side, that it is impossible to call PHP from JavaScript; however, this code snippet works:

<script>
  function otherCourse(){
    var course = prompt("prompt?");
    document.write("
      <?php
        $con->query("INSERT INTO `Courses` (`Name`) VALUES ('blah')");
      ?>
    ");
  }
</script>

Why does this work? The entry was inserted into the database

回答1:

Your PHP is being executed from the server side. Your PHP that you've embedded in the JavaScript never actually ends up rendering anything.

Test it by removing any calls to the otherCourse function, and you'll see that the query still runs.



回答2:

Your PHP executes on the server before that JavaScript even reaches the client.