PHP返回HTML标签的原因

时间:2017-12-12 18:41:05

标签: php html xmlhttprequest

好的,我有这个PHP代码:

SELECT * 
FROM vault
WHERE defendant_client LIKE (SELECT company FROM OpioidCompanies);

我用HTML调用这个脚本:

 <!doctype html>
<html>
  <body>
    <?php
      $q = intval($_GET['q']);
      $con = mysqli_connect('localhost', 'root', '', 'testDB');
      if(!$con){
        die('Could not connect: '. mysqli_error($con));
      }

      mysqli_select_db($con, "testDB");
      $query = "SELECT * FROM `aTable`;";
      $result = mysqli_query($con,$query);
      $row = mysqli_fetch_array($result);
      echo $row[$q];
      mysqli_close($con);
      exit();
     ?>
  </body>
</html>

为什么,控制台记录

 if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            var Response = this.responseText;
            console.log(Response);
        }
    };
    xmlhttp.open("GET", "script.php?q=1", true);
    xmlhttp.send();
}

我不知道为什么,但它会返回这些我不想要的HTML标签(只有-3到-1的值[带逗号])

如何删除(未关闭的)HTML标记?

感谢所有答案!

1 个答案:

答案 0 :(得分:0)

当您通过ajax调用script.php时,响应将包含您文件中的所有html标记,请务必将其全部删除。此外,您可能希望使用json_encode函数将php对象作为字符串发送到客户端,这是一个示例:

<强>的script.php

<?php
    $q = intval($_GET['q']);
    $con = mysqli_connect('localhost', 'root', '', 'testDB');
    if(!$con){
        die('Could not connect: '. mysqli_error($con));
    }

    mysqli_select_db($con, "testDB");
    $query = "SELECT * FROM `aTable`;";
    $result = mysqli_query($con,$query);
    $row = mysqli_fetch_array($result);
    echo json_encode($row[$q], true);
    mysqli_close($con);
    exit();

希望这有帮助