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

为什么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>
    
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本