XMLhttpRequest 返回空响应的问题

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

http://img2.mukewang.com/611f78ea000170fe08090589.jpg

http://img3.mukewang.com/611f78f20001814b17600329.jpg

这是我的 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';

    }

}


蓝山帝景
浏览 467回答 1
1回答

HUWWW

you miss place semicolon in xmlhttp request. please try below code and verify result&nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; function getRandomVar()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlhttp = new XMLHttpRequest();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlhttp.open("GET","demo1.php");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlhttp.send();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlhttp.onreadystatechange = function()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.readyState === 4 && this.status === 200)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var result = this.responseText;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(result);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //updateBackgroundColor(result);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script>&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript