Open Weather API使用JSON数据

时间:2016-07-01 20:26:23

标签: api openweathermap

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

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

1 个答案:

答案 0 :(得分:0)

$.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);
});
相关问题