weixin_33708432 2014-02-05 20:37 采纳率: 0%
浏览 604

为什么XMLHttpRequest不起作用?

我是javascript和AJAX新手,已经在此问题上花费了近8个小时,我知道它很简单,只是找不到我做错什么了。我的网站上有一个图片,带有on-click=SendCommand() 。这是我的js代码:

function SendCommand(){
        alert("BingoBango!");

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
        xmlhttp.send();
};

我会收到警报消息,但使用Firebug或chrome javascript控制台就不会有错误。而且,该页面未执行,但我可以将确切的URL复制并粘贴到浏览器中,并且可以成功执行。

  • 写回答

2条回答 默认 最新

  • weixin_33704591 2014-02-05 20:50
    关注

    This is how I would do it

    JS

    function SendCommand()
    {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
    xmlhttp.send();
    }
    

    HTML

    <button type="button" onclick="SendCommand()">My button</button>
    <div id="myDiv"></div>
    
    评论

报告相同问题?