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


How to use the response PHP variables in a XHR call?

我有两个页面,page1.php和page2.php。在page1.php我有一个按钮,当点击它使XHR调用page2.php,并显示在一个定义的划分即响应。

page .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;
?> 

我现在得到的输出,https://i.stack.imgur.com/WDdaa.jpg

我想对从page2获得的响应进行操作。比如我想在page1.php上用红色显示"apple"用蓝色显示"banana"

我该怎么做?

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 s。当然,您可以根据自己的需要编辑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";
?>