如何从JavaScript中调用PHP脚本

How to call PHP script from within JavaScript

本文关键字:调用 PHP 脚本 JavaScript      更新时间:2023-09-26

我需要帮助如何从JavaScript内部调用外部PHP脚本。下面是我的例子

index . php

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myName = 'John';
phpResult = /* Need help calling script.php passing is myName and assigning result to phpResult */;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
</script>
</body>
</html>

SCRIPT.PHP

<?php
    //script.php
        //Need help adding last name to John (i.e. Smith) and returning John Smith to calling javascript
?>

重要的事情先说:你所要求的事情不能用你所想的方式来完成。当请求页面时,服务器运行php文件,之后它将向您发送javascript/html/css页面。因此,当您看到页面时,php脚本已经完成了。Javascript在你的机器上运行,所以这就是为什么你可以用它来处理用户交互。

但是,如果您向script.php发送post请求,发送您想要的信息,那么您将能够与php文件进行交互。为此,需要使用jquery。下面是你如何在jquery中做到这一点的脚本:

$.ajax({
  type: "POST",
  url: "yoursite/script.php",
  data: "name="+myName,
  success: function(data){
phpResult = data;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
}
});

你可以从这里下载jquery: http://jquery.com/download/

下载后,你必须把它链接到你的index.php jquery.js文件,作为一个普通的javascript文件。

在你的php文件中,你可以用$_POST["name"]访问这个名字,而你想要发送回来的信息,你必须打印出来。像这样:

if(isset($_POST["name"])){
$result = "";
//Do something with the name, and fill accordingly the $result variable
// Something like:
$result = $_POST["name"]." Smith";
echo $result;
}

你可以直接写

phpResult = '<?php echo $sometext; ?>';

,

  • js脚本需要在php文件中。你不能在。js文件中使用这个。
  • 这将不会在客户端计算任何运行时变量。因为页面已经包含了php脚本从服务器渲染的变量。

我一直使用这个方法,特别是在将php数组和对象渲染为js对象/数组时。