I am trying to fetch information from a JSON file but nothing comes in the data variable. Can anyone tell me what I am doing wrong. The JSON file is downloaded so there is no problem with me not getting anything from the server.
function handle_geolocation_query(position) {
var url = "http://ws.geonames.org/findNearByWeatherJSON?lat=" + position.coords.latitude + "&lng=" + position.coords.longitude + "&callback=?";
$.getJSON(url, function(info){
var clouds = info.weatherObservation.clouds;
var weather = info.weatherObservation.weatherCondition;
var temp = info.weatherObservation.temperature;
var humidity = info.weatherObservation.humidity;
});
//console.log(clouds);
document.getElementById('result').innerHTML = "C:" + clouds + ", W:" + weather + ", T:" + tem开发者_如何学编程p + ", H:" + humidity;
}
Appreciate all the help. Thanks a lot.
You should try placing the code that modifies the innerHTML within the callback. Remember that JS has function scope. You can't access these variables outside. Also, those variables are set only after callback from retrieving the JSON is executed.
function handle_geolocation_query(position) {
var url = "http://ws.geonames.org/findNearByWeatherJSON?lat=" + position.coords.latitude + "&lng=" + position.coords.longitude + "&callback=?";
$.getJSON(url, function(info){
var clouds = info.weatherObservation.clouds;
var weather = info.weatherObservation.weatherCondition;
var temp = info.weatherObservation.temperature;
var humidity = info.weatherObservation.humidity;
$('#result').html("C:" + clouds + ", W:" + weather + ", T:" + temp + ", H:" + humidity);
});
}
Edit: Following gov's advice, you should use the jQuery API's encapsulated html() method whenever you find the need to change innerHTML.
Also, you can use:
console.log(info);
while debugging in the getJSON callback just to ensure your data is structured the way you think it is.
try to do the below, i think it may be coming as array of objects
var clouds = info.weatherObservation.clouds;
var weather = info[0].weatherObservation.weatherCondition;
var temp = info[0].weatherObservation.temperature;
var humidity = info[0].weatherObservation.humidity;
精彩评论