openweathermap通过邮政编码的天气数据不起作用?

时间:2018-11-09 16:19:17

标签: javascript jquery weather openweathermap

我需要这样做,以便在框中输入邮政编码并单击提交按钮时,城市名称将显示在其下。当我在输入邮政编码后单击按钮时,城市名称不会显示。它说错误是wallOfText不是一个函数,但我不确定如何修复它。任何帮助,将不胜感激!!这是代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <meta charset="UTF-8">
    <title>Example</title>
</head>
<body>
Enter your zip code:<br><input type="text" id="zipBox" name="zipCode"><br><br>
<button onclick="weatherFunction()">Submit</button>
<p id="result"></p>
<script>
    function weatherFunction() {
        var zip = document.getElementById("zipBox").value;
        jQuery(document).ready(function ($) {
            $.ajax({
                url: "http://api.openweathermap.org/data/2.5/weather?zip=" +zip+ ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
                dataType: "jsonp",
                success: function (wallOfText) {
                    city = wallOfText("name");
                    if (zip != null) {
                        document.getElementById("result").innerHTML = wallOfText;

                    }
                }
            });
        });
    }
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,您试图像函数一样调用wallOfText,而实际上这是从AJAX调用响应中反序列化的对象。这样,您需要访问对象的name属性来设置city变量,然后使用该属性来设置text()元素的#result

请注意,函数中的document.ready处理程序是多余的,因此在发出请求之前,您应该先进行zip值验证 。我还更新了使用jQuery绑定按钮上的事件处理程序而不是过时的onclick属性的逻辑。试试这个:

jQuery(function() {
  $('#send').click(function() {
    var zip = $("#zipBox").val();
    if (zip !== '') {
      $.ajax({
        url: "http://api.openweathermap.org/data/2.5/weather?zip=" + zip + ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
        dataType: "jsonp",
        success: function(wallOfText) {
          var city = wallOfText.name;
          $("#result").text(city);
        }
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your zip code:<br>
<input type="text" id="zipBox" name="zipCode" value="90210" /><br /><br /> 
<button type="button" id="send">Submit</button>
<p id="result"></p>