如何在XHR调用中使用响应PHP变量?

时间:2015-05-28 06:05:43

标签: javascript php ajax xmlhttprequest

我有两页说,page1.php和page2.php。在page1.php中我有一个按钮,当点击它时,它会对page2.php进行XHR调用,并在定义的divison中显示响应,即在page1中显示“print”。

page1.php的代码

<html>
    <button type="button" onclick="randomFunction()">Request data</button>
    <div id="print"></div>
    <script type="text/javascript">
        function randomFunction()
        {
        var xmlhttp;
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
          document.getElementById("print").innerHTML=xmlhttp.responseText;
          }
        }
        xmlhttp.open("POST","page2.php",true);
        xmlhttp.send();
        }
    </script>
</html>

page2.php的代码

<?php
$a = "apple";
$b = "banana";
echo $a;
echo $b;
?> 

我现在收到的输出,http://imgur.com/tyqEOgW

我想操纵我从第2页获得的响应。就像在我想要以红色显示“apple”和在page1.php上显示蓝色的“banana”

我该怎么做?

1 个答案:

答案 0 :(得分:1)

page2.php发回JSON,然后将包含该数据的自定义HTML添加到page1.php

<强> page1.php中

<html>
    <button type="button" onclick="randomFunction()">Request data</button>
    <div id="print"></div>
    <script type="text/javascript">
        function randomFunction()
        {
          var xmlhttp;
          if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
          }
          else
          {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }

          xmlhttp.onreadystatechange=function()
          {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
              var data = JSON.parse(xmlhttp.responseText);
              var html = '<span class="apple">'+data.a+'</span><span class="banana">'+data.b+'</span>';

              document.getElementById("print").innerHTML = html;
            }
          }

          xmlhttp.open("POST","page2.php",true);
          xmlhttp.send();
        }
    </script>
</html>

<强>使page2.php

<?php
  $a = "apple";
  $b = "banana";

  echo json_encode( array( 'a' => $a, 'b' => $b ) );
?> 

现在你可以按照自己的意愿设置这些span的样式。当然,您可以根据自己的需要编辑HTML结构。

仅PHP

<强> page1.php中

<html>
    <a href="?showData=1">Request data</a>
    <div id="print">
        <?php
        // Show data only, if our link was clicked
        if( $_GET['showData'] == 1 ){
            // Get page2.php
            require_once('page2.php');

            echo '<span class="apple">'.$a.'</span><span class="banana">'.$b.'</span>';
        }
        ?>
    </div>
</html>

<强>使page2.php

<?php
  $a = "apple";
  $b = "banana";
?>