【问题标题】:Cannot set property 'innerHTML' of null at XMLHttpRequest.xhttp.onreadystatechange无法在 XMLHttpRequest.xhttp.onreadystatechange 处将属性“innerHTML”设置为 null
【发布时间】:2020-09-09 01:59:02
【问题描述】:

我在这段代码中遇到错误,应该等于内部 html

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function()
      {
        if (this.readyState == 4 && this.status == 200)
       {
          document.getElementById("id").innerHTML = `enter code here`;
       }
      };
            xhttp.open("GET","https://api.openweathermap.org/data/2.5/weatherq=London,uk&appid=2ed23a9e218c67041a6853dec1eb24da", true);
          xhttp.send();

【问题讨论】:

    标签: javascript html ajax innerhtml


    【解决方案1】:

    您的代码使用不同的端点似乎很好,见下文。该 url 需要一个 有效的 API 密钥,也许你没有在你的请求中发送它。

    服务器响应有状态 401 和消息:

    {
      "cod":401,
       "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."
    }
    

    var xhttp = new XMLHttpRequest();
                
                
      xhttp.onreadystatechange = function()
          {
            if (this.readyState == 4 && this.status == 200)
           {
              document.getElementById("id").innerHTML = `enter code here`;
           }
          };
          xhttp.open("GET","https://api.openweathermap.org/data/2.5/weatherq=London,uk&appid=2ed23a9e218c67041a6853dec1eb24da", true);
              xhttp.send();
    <div id="id">
    
    </div>

    【讨论】:

    • 2ed23a9e218c67041a6853dec1eb24da 这是 api 密钥
    • 嘿,现在我检查了它现在是否有效,但我得到的只是这个.... 加载资源失败:服务器响应状态为 404(未找到)api.openweathermap.org/data /2.5/weatherq=London,uk&appid=2ed23a9e218c67041a6853dec1eb24da:1 加载资源失败:服务器响应状态为 401(未授权)
    • 尝试将weatherq 更改为weather?q - GET 查询字符串必须以 ? 开头
    • Uncaught ReferenceError: Weather is not defined at XMLHttpRequest.xhttp.onreadystatechange...在第 17 行仍然不知道出了什么问题。
    【解决方案2】:

    HTML 尚未加载

    要么使用 onload 事件,要么将脚本放在正文的末尾

      <body>
        <div>
          <span>The current weather in London is: </span><span id="id"></span>
        </div>
        <script>
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
              document.getElementById("id").innerHTML = `enter code here`;
            }
          };
          xhttp.open(
            "GET",
            "https://api.openweathermap.org/data/2.5/weatherq=London,uk&appid=2ed23a9e218c67041a6853dec1eb24da",
            true
          );
          xhttp.send();
        </script>
      </body>
    

    【讨论】:

    • 你能指导我吗?
    • 我已经在上面的答案中添加了代码,当然你仍然需要一个有效的 openweathermap api 密钥才能向你发送所需的响应你可以注册并将 api 密钥添加到你的查询字符串中,如下所示@ 987654321@
    猜你喜欢
    • 1970-01-01
    • 2014-08-25
    • 2013-08-16
    • 2021-05-23
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多