4

我正在尝试使用 XMLHttpRequest 将变量传递给 php 脚本,然后让 php 回显它。我不明白为什么它不起作用,有人可以帮助我。这是Javascript。

<script language="javascript" type="text/javascript">
    // Browser Support 
function Heatctrl(heatMode){
    var heatControlRequest;

    try{
        //Good Browsers
        heatControlRequest = new XMLHttpRequest();
    } catch (e) {
        //Internet Explorer
        try{
            heatControlRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                heatControlRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e) {
                alert("Brower not supported");
                return false;
            }
        }
    }


    // Function to receive data from server and store in variable
    heatControlRequest.onreadystatechange = function(){
        if (heatControlRequest.readystate == 4){
            alert(heatControlRequest.responseText);
            //document.getElementById("controlMode").innerHTML=heatControlRequest.responseText;
            //var heatControlResponse = heatControlRequest.responseText;
        }
    }
    var url = "heatControl.php?heatmode="+heatMode;
    // Send the request
    heatControlRequest.open("GET", url, true);
    heatControlRequest.send();
}   
</script>

的HTML

    <div id="boilerButtons">
    <button type="button" onclick="Heatctrl('On')">Heating On</button>
    <button type="button" onclick="Heatctrl('Off')">Heating Off</button>
    <button type="button" onclick="Heatctrl('Boost')">Boost</button>
</div>

和PHP

<?php
$controlMode = $_GET['heatmode'];
echo $controlMode; 
?>

非常感谢任何帮助,我从事电子工作而不是编程,我已经为此苦苦挣扎了两天。

4

1 回答 1

3

问题是这一行:

if (heatControlRequest.readystate == 4){
                            ^ this should be an uppercase S

它应该是:

if (heatControlRequest.readyState == 4){ 

文档

XMLHttpRequest 对象可以处于多种状态。readyState 属性必须返回当前状态。

于 2012-11-27T16:41:57.163 回答