XMLHttpRequest passing a variable to php script

回眸只為那壹抹淺笑 提交于 2019-12-22 09:00:11

问题


I am trying to pass a variable to a php script using XMLHttpRequest and then have the php echo it back. I can't understand why it isn't working, could someone please help me. Here is the 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>

and the php

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

Any help is much appreciated, I work in electronics not programming and I've been struggling with this now for two days.


回答1:


The problem is this line:

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

It should be:

if (heatControlRequest.readyState == 4){ 

From the docs:

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state.



来源:https://stackoverflow.com/questions/13588301/xmlhttprequest-passing-a-variable-to-php-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!