【问题标题】:XMLHttpRequest passing a variable to php scriptXMLHttpRequest 将变量传递给 php 脚本
【发布时间】:2012-11-15 07:32:23
【问题描述】:

我正在尝试使用 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; 
?>

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

【问题讨论】:

  • html文件和php文件在同一个目录
  • 什么是“不工作”?是否正在提出请求?您的 JavaScript 控制台中是否有错误?你的Heatctrl 函数正在运行吗?
  • P.S.不要在&lt;script&gt; 标签中使用language="javascript"

标签: php javascript xmlhttprequest


【解决方案1】:

问题出在这一行:

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

应该是:

if (heatControlRequest.readyState == 4){ 

来自docs

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

【讨论】:

  • 很好,非常感谢。只是出于兴趣,有什么理由没有在 Chrome 的 javascript 控制台中显示为错误?
  • 不客气。 Javascript 允许您像这样检查对象的未定义属性的值而不会引发错误。
猜你喜欢
  • 1970-01-01
  • 2013-12-27
  • 2011-11-18
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
相关资源
最近更新 更多