【问题标题】:XMLHttpRequest, working in Excel VBA, not working in javascript/htmlXMLHttpRequest,在 Excel VBA 中工作,不在 javascript/html 中工作
【发布时间】:2019-11-14 22:06:44
【问题描述】:

我正在尝试将 opendata 从网站获取到我自己的网站。我正在使用此代码(从 w3schools 示例中获取)并尝试将其与我在 Excel/VBA 中的工作代码结合起来。 但不知何故,我无法让它在我的网站上运行......我的 html/javascript 中缺少什么?

HTML:https://codepen.io/1234cb/pen/ZEEqxJK

<body>
<h1>XMLHttpRequest</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState > 1) {
      document.getElementById("demo").innerHTML =
            this.responseText;
    }
  };
  xhttp.open("POST", "https://www.energielabel.nl/api/v1/checkenergylabel", false);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
  xhttp.setRequestHeader("Connection", "Keep-Alive");
  xhttp.send("Postcode=2651ES&HouseNr=109&HouseNrAddition=");

document.getElementById("demo").innerHTML = this.responseText;

}
</script>
</body>
</html>

VBA:

Sub getopendata()
Set ObjHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "https://www.energielabel.nl/api/v1/checkenergylabel"
ObjHTTP.Open "POST", URL, False
ObjHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
ObjHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
ObjHTTP.setRequestHeader "Connection", "Keep-Alive"
ObjHTTP.send ("Postcode=2651es&HouseNr=109")
ActiveCell = ObjHTTP.responsetext
Set ObjHTTP = Nothing
Set xmlDoc = Nothing
End Sub

【问题讨论】:

    标签: javascript html ajax vba request


    【解决方案1】:

    你在哪里

    xhttp.send("Postcode=2651ES&HouseNr=109&HouseNrAddition=");
    
    document.getElementById("demo").innerHTML = this.responseText;
    

    您必须删除此行:document.getElementById("demo").innerHTML = this.responseText;,因为您已经在 onreadystatechange 回调中处理了 responseText。

    【讨论】:

    • Tnx 安德鲁!试图删除该行,似乎没有任何效果..
    • 我试过你的代码没有那行,它可以工作。你的代码也有效吗?如果是,请接受我的回答。
    • 很抱歉,如果我在 [link]codepen.io/1234cb/pen/ZEEqxJK 尝试这个,我看不到任何结果
    • 请检查您的 JS 控制台,那里记录了错误和警告。此外,在 codepen 上不允许 CORS 请求。
    • codepen 可能是个问题。 Chrome 提到 CORS 问题:请求的资源上不存在“Access-Control-Allow-Origin”标头。并且:加载资源失败:服务器响应状态为 415(不支持的媒体类型)。也发生在 EDGE 中。在IE下完全没有问题,完美显示结果。
    猜你喜欢
    • 2017-10-09
    • 2013-03-03
    • 2016-07-04
    • 2019-09-06
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多