XMLHttpRequest将变量传递给php脚本 [英] XMLHttpRequest passing a variable to php script

查看:143
本文介绍了XMLHttpRequest将变量传递给php脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

我非常感谢任何帮助,我从事电子工作而不是编程,我现在一直在努力两天。

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

推荐答案

问题是这一行:

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

它应该是:

if (heatControlRequest.readyState == 4){ 

来自 docs


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

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

这篇关于XMLHttpRequest将变量传递给php脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆