2010-12-01 50 views
0

我想从JSON文件中获取信息,但数据变量中没有任何内容。任何人都可以告诉我我做错了什么。 JSON文件被下载,所以没有问题,我没有从服务器获取任何东西。jQuery JSON获取问题

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:" + temp + ", H:" + humidity; 
} 

欣赏所有的帮助。 非常感谢。

+2

与萤火虫可以检查网面板,是回馈您正在访问同一个结构上的JSON标签的阵列。 – kobe 2010-12-01 05:55:25

+0

无论如何,你正在使用jQuery,使用.html()而不是.innerhtml,你可以simloy say('#result')。html();是weatherObservation一个对象或单个对象的数组。 – kobe 2010-12-01 05:56:29

回答

0

您应该尝试将修改innerHTML的代码放在回调中。记住JS有函数范围。你不能在外面访问这些变量。另外,这些变量只有在执行检索JSON的回调后才会设置。

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); 
    }); 
} 

编辑:继GOV的建议,你应该使用jQuery的API的封装HTML()方法,无论何时你发现需要改变的innerHTML。

此外,您还可以使用:

console.log(info); 

而在回调的getJSON调试只是为了确保你的数据是结构化的,你觉得是这样的。

0

尝试做以下,我认为这可能是未来为对象

var clouds = info.weatherObservation.clouds; 
     var weather = info[0].weatherObservation.weatherCondition; 
     var temp = info[0].weatherObservation.temperature; 
     var humidity = info[0].weatherObservation.humidity;