【问题标题】:openweathermap weather data by zip code not working?邮政编码的openweathermap天气数据不起作用?
【发布时间】:2019-04-13 05:54:48
【问题描述】:

我需要这样做,以便当在框中输入邮政编码并单击提交按钮时,城市名称会显示在其下方。当我输入邮政编码后单击按钮时,城市名称不显示。它说错误是 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>

【问题讨论】:

    标签: javascript jquery weather openweathermap


    【解决方案1】:

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

    请注意,函数中的 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>

    【讨论】:

      猜你喜欢
      • 2013-12-12
      • 2015-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多