JavaScript传递变量并从PHP页面检索输出

JavaScript to Pass variable and retrieve output from PHP page

本文关键字:PHP 面检索 输出 变量 JavaScript      更新时间:2023-09-26

尝试将变量传递到PHP文件,然后获得该文件的输出。

Page1.html:

 <h2 id="test"></h2>
 <script>
 var data2;
 $.post('textandemail.php',{ txt: "John", email: "test@gmail.com" },
  function(data) {
 data2 = data;});
 document.getElementById("test").innerHTML = data2;
 </script>

textandemail.php:

  $variable = $_POST["txt"];
  $variable2 = $_POST["email"];
  echo $variable;
  echo $variable2;    

希望这能描述出想要的想法。我将在PHP文件中做更多的工作,但最终会返回一个响应,我希望JavaScript读取该响应并将其实现到html页面中。

$.post()函数是异步的。它稍后结束。您需要将该函数的结果分配到成功处理程序中,而不是在函数本身之后,因为现在,行document.getElementById("test").innerHTML = data2;发生在ajax函数完成之前,因此它无法工作。

这就是你可以做到的:

<h2 id="test"></h2>
 <script>
 $.post('textandemail.php',{ txt: "John", email: "test@gmail.com" },
    function(data) {
       // any code that uses the ajax results in data must be here
       // in this function or called from within this function
       document.getElementById("test").innerHTML = data;
    }
  );
 </script>

或者,既然你有jQuery,你可以这样做:

<h2 id="test"></h2>
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
 <script>
 $.post('textandemail.php',{ txt: "John", email: "test@gmail.com" },
    function(data) {
       // any code that uses the ajax results in data must be here
       // in this function or called from within this function
       $("#test").html(data);
    }
  );
 </script>

您的post调用是异步的,只有在进程完成后才能访问data2变量,因此您应该在数据可用时而不是之前在回调函数中执行....innerHTML ...

在任何js网站上都有很多这样的好例子。在jQuery文档中,您有一个很好的例子。由于您正在使用jQuery,您也可以替换innerHTML调用。

您应该使用ajax函数在php和javascript 之间进行通信

 function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){
var xmlhttp
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}
catch(e){
try{xmlhttp=new XMLHttpRequest()}
catch(e){
alert("Your Browser Does Not Support AJAX")}}}
err=""
if (GP==undefined) err="GP "
if (URL==undefined) err +="URL "
if (PARAMETERS==undefined) err+="PARAMETERS"
if (err!=""){alert("Missing Identifier(s)'n'n"+err);return false;}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if (RESPONSEFUNCTION=="") return false;
eval(RESPONSEFUNCTION(xmlhttp.responseText))
}
}
if (GP=="GET"){
URL+="?"+PARAMETERS
xmlhttp.open("GET",URL,true)
xmlhttp.send(null)
}
if (GP="POST"){
PARAMETERS=encodeURI(PARAMETERS)
xmlhttp.open("POST",URL,true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.setRequestHeader("Content-length",PARAMETERS.length)
xmlhttp.setRequestHeader("Connection", "close")
xmlhttp.send(PARAMETERS)    

调用函数将其放入javascript页面中

Ajax_Send("POST","users.php",data,e)

其中data是您发送到php页面的数据,e是您将php页面的输出传递给它的函数