【问题标题】:Not getting data using JSON from openweather.com未使用来自 openweather.com 的 JSON 获取数据
【发布时间】:2017-09-09 02:51:23
【问题描述】:

我正在尝试借助地理位置(纬度和经度)从 openweather.com api 获取天气信息。我不明白为什么它没有获取数据。这是我的代码:

function getWeather(lat, long){
  console.log(lat +" "+ long); //23.8008983 90.3541741
  $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8", function(json) {  
    console.log("Successfully data recieved");
    var temp = Math.round(json.main.temp);
    console.log(temp);
    $("#weather").value(temp);
  });

我尝试在控制台中打印“已成功接收数据”,但没有打印。我假设回调没有发生。确认函数调用 (getWeather()) 没问题,因为我正在获取纬度和经度值(我将这些值保留在评论中)。我非常需要你的帮助。我在浏览器中手动输入了带有纬度和经度的 url,它返回了我应该从这个 JSON 调用中获得的预期输出。但不能在代码中工作。

【问题讨论】:

  • 在此代码中,您的函数没有结束标记(我必须编辑问题以更正缩进,现在您可以看到它)。会不会是这个原因?

标签: javascript jquery json ajax


【解决方案1】:

我对此搞砸了一段时间,并意识到有时这是最简单的解决方案...尝试请求安全 (https) URL:

$.getJSON("https://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8", function(json) {  
    console.log("Successfully data recieved");
    var temp = Math.round(json.main.temp);
    console.log(temp);
    $("#weather").value(temp);
  });

【讨论】:

    【解决方案2】:

    你的函数没有正确关闭,你错过了结束 } 大括号(我猜这是一个错字)。我试过你的代码,它对我很有用。还要确保您的 `jquery 库被完美包含。

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>jQuery.getJSON demo</title>
        <style>
            img {
                height: 100px;
                float: left;
            }
        </style>
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
    <script>
        (function() {
            getWeather(23.8008983,90.3541741);
        })();
    
    
        function getWeather(lat, long){
            var watherAPI = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8";
            $.getJSON( watherAPI, function (json) {
                console.log("Successfully data recieved");
                var temp = Math.round(json.main.temp);
                console.log(temp);
            })}
    </script>
    
    </body>
    </html>
    

    【讨论】:

    • "https" 顺便给了我解决方案。
    • @Mohammad Nakib ,但我得到的数据没有 https,只是使用 http。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2017-04-09
    • 1970-01-01
    相关资源
    最近更新 更多