开放天气 API 使用 JSON 数据

Open Weather API use JSON data

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 并使用 Open weather 来获取城市的天气。 当我使用 getJSON 分配我猜想的数据值时,问题就开始了。 我收到这个错误。 :未捕获的语法错误:JSON 中位置 0

中的意外标记 u

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

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

试试这个:

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