【问题标题】:Problem with XMLhttpRequest returning empty responseXMLhttpRequest 返回空响应的问题
【发布时间】:2019-07-25 03:06:11
【问题描述】:

我正在尝试在我的网站中构建一个新功能,该功能需要我从我的网络服务器上的数据库中检索单个值。 为此,我使用了一个 php 脚本服务器端,它使用 msqli 从数据库中检索数据。客户端我使用 Ajax 和 XMLhttpRequest 来调用 php 脚本。一切正常,我没有任何错误,除了我的 xml 总是有一个空响应,这让我觉得我的 php 脚本有问题。你们能帮忙吗?生病包括下面的一些代码。

screenshot of my xmlhttprequest

screenshot of my network tab

这是我的 php 脚本

<?php


$conn = new mysqli('localhost', 'nicolas', 'Password', 'RandomNumberHouse');

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    echo "error";
} 

$HouseID = 6;

$sql = "SELECT RandomVar FROM RandomVarHouse WHERE HouseID = $HouseID";

$result = $conn->query($sql);
$row = mysqli_fetch_array($result);
$var = $row[2];
echo $var;
$conn-> close();

?>

这是我的 js 脚本

function getRandomVar(){
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET","../inc/VarCommunication.php?");
    xmlhttp.send();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            var result = this.responseText;
            updateBackgroundColor(result);
        };
      }
}   


function updateBackgroundColor(number){
    if( number < 100){
        document.getElementById('mainBody').style.backgroundColor = 'red';
    }
}

【问题讨论】:

  • 浏览器开发人员工具中的“网络”选项卡告诉您有关 HTTP 响应的哪些信息?
  • 我只得到200状态
  • 欢迎来到 SO!控制台或终端中是否有任何错误消息可以添加到您的问题中?
  • 这就是奇怪的部分,我没有任何错误,我认为问题一定是我的 php 脚本的输出,但我找不到任何错误
  • 我应该添加网络选项卡的屏幕截图和 xmlhttprequest 的内容吗?

标签: javascript php mysql xmlhttprequest


【解决方案1】:
you miss place semicolon in xmlhttp request. please try below code and verify result

  <script>
        function getRandomVar()
        {
            xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET","demo1.php");
            xmlhttp.send();
            xmlhttp.onreadystatechange = function()
            {
                if (this.readyState === 4 && this.status === 200)
                {
                    var result = this.responseText;
                    alert(result);
                    //updateBackgroundColor(result);
                }
              };
        }

    </script> 

【讨论】:

  • 哦,哇,原来如此,谢谢您的帮助!我真愚蠢,没有看到那个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 2012-03-23
  • 2020-09-25
  • 1970-01-01
  • 2020-08-29
相关资源
最近更新 更多