json API调用中未显示结果

wn9m85ua  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(148)

我正在尝试调用天气API,但由于某种原因,我无法在控制台和网页上看到结果后,进入一个特定的城市
我打过电话

<div id="results"></div>

并确保在我的脚本中声明它。有人能帮忙吗?
更新:当我把它们合并成一个文件时,代码可以工作。但是当我把它们分成两个不同的文件时,代码就不能工作了。我在这里遗漏了什么?
这是代码的script.js

var cityform = document.getElementById("cityform");
  
      // Check if the cityform variable is not null
      if (cityform !== null) {
        // Add a submit event listener to the form
        cityform.addEventListener("submit", function(event) {
          // Prevent the default form submission behavior
          event.preventDefault();
  
          // Get a reference to the input element
          var cityInput = document.getElementById("thecity");
  
          // Check if the cityInput variable is not null
          if (cityInput !== null) {
            // Get the input value
            var city = cityInput.value;
  
            // Make the API request using the city value
            $.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data){
  
            console.log(data);
  
              // Extract the data from the API response
              var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
              var temp = Math.floor(data.main.temp) + "F"; 
              var weather = data.weather[0].main;
  
              // Get a reference to the element where the data will be displayed
              var results = document.getElementById("results");
              
              // Update the element with the data from the API
              results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
            });
          }
        });
      }

下面是HTML

<head>
    <meta charset="UTF-8">
    <meta name ="viewport" content="width=device=width, intial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content ="is=edge">
    <title>API</title>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

    <script src = "script.js"></script>
   

</head>

<body>
    <!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
  <label for="thecity">City:</label><br>
  <input type="text" name="thecity" id="thecity"><br><br>
  <button type="submit">Search</button>
</form>

<!-- Create an element where the data will be displayed -->
<div id="results"></div>

</body>
</html>

可能的问题是什么,或者如果没有问题,你怎么能显示图标的结果,温度和天气的“结果”

but5z9lq

but5z9lq1#

script.js链接部分粘贴到末尾。有可能当你的脚本运行时,窗体没有被创建,因此那些变量当时并不存在。

请参阅两个示例,此方法有效

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device=width, intial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="is=edge">
        <title>API</title>
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
      </head>
      <body>
        <!-- HTML -->
        <h1>Weather Report</h1>
        <form id="cityform">
          <label for="thecity">City:</label>
          <br>
          <input type="text" name="thecity" id="thecity">
          <br>
          <br>
          <button type="submit">Search</button>
        </form>
        <!-- Create an element where the data will be displayed -->
        <div id="results"></div>
        
        <script>

          var cityform = document.getElementById("cityform");

          // Check if the cityform variable is not null
          if (cityform !== null) {
              // Add a submit event listener to the form
              cityform.addEventListener("submit", function(event) {
                  // Prevent the default form submission behavior
                  event.preventDefault();

                  // Get a reference to the input element
                  var cityInput = document.getElementById("thecity");

                  // Check if the cityInput variable is not null
                  if (cityInput !== null) {
                      // Get the input value
                      var city = cityInput.value;

                      // Make the API request using the city value
                      $.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {

                          console.log(data);

                          // Extract the data from the API response
                          var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
                          var temp = Math.floor(data.main.temp) + "F";
                          var weather = data.weather[0].main;

                          // Get a reference to the element where the data will be displayed
                          var results = document.getElementById("results");

                          // Update the element with the data from the API
                          results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
                      });
                  }
              });
          }
          
        </script>
        
      </body>
    </html>

但不是这样

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device=width, intial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="is=edge">
        <title>API</title>
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

        <script>

          var cityform = document.getElementById("cityform");

          // Check if the cityform variable is not null
          if (cityform !== null) {
              // Add a submit event listener to the form
              cityform.addEventListener("submit", function(event) {
                  // Prevent the default form submission behavior
                  event.preventDefault();

                  // Get a reference to the input element
                  var cityInput = document.getElementById("thecity");

                  // Check if the cityInput variable is not null
                  if (cityInput !== null) {
                      // Get the input value
                      var city = cityInput.value;

                      // Make the API request using the city value
                      $.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {

                          console.log(data);

                          // Extract the data from the API response
                          var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
                          var temp = Math.floor(data.main.temp) + "F";
                          var weather = data.weather[0].main;

                          // Get a reference to the element where the data will be displayed
                          var results = document.getElementById("results");

                          // Update the element with the data from the API
                          results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
                      });
                  }
              });
          }
          
        </script>

      </head>
      <body>
        <!-- HTML -->
        <h1>Weather Report</h1>
        <form id="cityform">
          <label for="thecity">City:</label>
          <br>
          <input type="text" name="thecity" id="thecity">
          <br>
          <br>
          <button type="submit">Search</button>
        </form>
        <!-- Create an element where the data will be displayed -->
        <div id="results"></div>
        

      </body>
    </html>

如果要检查自己,则在var cityform = document.getElementById("cityform");之后添加alert(cityform)
当脚本链接位于head before body中时,我们将在alert中获得null,但当脚本位于结尾靠近关闭body标记时,alert将具有form元素。
希望有帮助。如果我哪里错了,请评论。

0x6upsns

0x6upsns2#

您需要将script从HTML中body内的head位置移动
此代码有效

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device=width, intial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="is=edge">
    <title>API</title>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"
        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

</head>

<body>
    <!-- HTML -->
    <h1>Weather Report</h1>
    <form id="cityform">
        <label for="thecity">City:</label><br>
        <input type="text" name="thecity" id="thecity"><br><br>
        <button type="submit">Search</button>
    </form>

    <!-- Create an element where the data will be displayed -->
    <div id="results"></div>

    <script src="script.js"></script>

</body>

</html>
function resultSubmit(event) {
    event.preventDefault();
    // Get the input value
    var city = cityInput.value;

    // Make the API request using the city value
    $.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function (data) {

        console.log(data);

        // Extract the data from the API response
        var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
        var temp = Math.floor(data.main.temp) + "F";
        var weather = data.weather[0].main;

        // Update the element with the data from the API
        results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
    });
}

const cityform = document.getElementById("cityform");
const cityInput = document.getElementById("thecity");
const results = document.getElementById('results')

cityform.addEventListener('submit', resultSubmit)

结果-我在VS代码中运行了GO Live扩展

相关问题