2016-07-01 6 views
0
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:JSONの位置0で予期しないトークンuOpen Weather APIはJSONデータを使用します

これは私のデータ変数がここでは定義されていないことを意味しています。私はここで間違って何をしていますか?

答えて

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); 
}); 
関連する問題