XMLHttpRequest将变量传递给php脚本

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>

The 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; 
?>

非常感谢任何帮助,我从事电子工作而非编程,这个问题已经困扰我两天了。


HTML文件和PHP文件位于同一目录中。 - GBD
“不工作”是指什么?是否发出了请求?您的JavaScript控制台中是否有错误?您的Heatctrl函数是否正在运行? - gen_Eric
请勿在您的<script>标签中使用language="javascript" - gen_Eric
1个回答

3
问题在于这行代码:
if (heatControlRequest.readystate == 4){
                            ^ this should be an uppercase S

应该是:

if (heatControlRequest.readyState == 4){ 

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


太好了,成功了,非常感谢。顺便问一下,为什么这个错误在Chrome的JavaScript控制台中没有显示出来呢? - ironcrow
不用谢。Javascript 允许你检查对象的未定义属性的值,而不会引发错误。 - ServerBloke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接