【问题标题】:Open Weather API use JSON dataOpen Weather API 使用 JSON 数据
【发布时间】:2016-11-04 08:09:12
【问题描述】:
var weather;
$(document).ready(function(){
alert("wellco");
var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";
document.body.appendChild(canvas);

 //the part where things go wrong begins
data = $.getJSON('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=c5959a33372923c74fccc1d07ab4b37b&units=metric');
weather=JSON.parse(data.responseText);
console.log(weather.main.temp);
if(data!="undefined"){
$('#temp').textContent = weather.main.temp;
}
});

所以我正在开发 chromeExtension 并使用开放天气来获取城市的天气。 当我使用 getJSON 分配数据值时,问题就开始了。 我得到这个错误。 : Uncaught SyntaxError: 位置 0 处 JSON 中的意外标记 u

我在某处读到这意味着我的数据变量在这里未定义。我在这里做错了什么?

【问题讨论】:

    标签: api openweathermap


    【解决方案1】:

    $.getJSON() 是异步的;它不会像您尝试的那样作为函数调用的结果返回值。相反,提供一个回调函数来处理返回的数据。最后,JSON 已经为您解析成一个对象。

    试试这个:

    $.getJSON('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=c5959a33372923c74fccc1d07ab4b37b&units=metric', function (weather) {
        console.log(weather.main.temp);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-20
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多