在我的Titanium天气项目中,我想解析json数据并在我的项目中显示数据,但我无法做到。我努力但却一直在努力。
这是我的代码,有什么问题?请有人帮助我。
var win = Titanium.UI.createWindow({
backgorundColor: '#000',
title: 'My Weather App'
});
var tableview = Ti.UI.createTableView();
var data = [];
var xhr = Ti.Network.createHTTPClient({
onload: function () {
alert("success!");
var json = JSON.parse(this.responseText);
for (var i = 0; i < json.observation_location.length; i++) {
//data.push({"country":json.observation_location[i].country,"city":json.observation_location[i].city});
var row = Ti.UI.createTableViewRow({
height: 60,
//filter:observation_location[i].
});
var countryLabel = Ti.UI.createLabel({
text: json.observation_location[i].country,
height: 'auto',
left: 10,
top: 5,
});
var cityLabel = Ti.UI.createLabel({
text: json.observation_location[i].city,
height: 'auto',
left: 15,
});
row.add(countryLabel);
row.add(cityLabel);
data.push(row);
}
tableview.setData(data);
},
onerror: function () {
alert('There was an error retrieving the remote data. Try again.');
}
//timeout:5000
});
xhr.open("GET", "http://api.wunderground.com/api/02e5dd8c34e3e657/geolookup/conditions/forecast/q/Dhaka,Bangladesh.json");
xhr.send();
win.add(tableview);
win.open();
答案 0 :(得分:0)
返回的JSON似乎不是数据数组。您可以通过在调试中运行应用程序并在分配json变量后立即设置断点来检查此问题。然后,您可以导航返回的数据。虽然返回了很多信息,但它们都没有特别像数组,所以我删除了你的循环。另外,observation_location位于current_observation内,因此您可以通过 json.observation_location.current_observation 访问它。
var win = Titanium.UI.createWindow({
backgorundColor: '#000',
title: 'My Weather App'
});
var tableview = Ti.UI.createTableView();
var data = [];
var xhr = Ti.Network.createHTTPClient({
onload: function () {
alert("success!");
var json = JSON.parse(this.responseText);
//for (var i = 0; i < json.observation_location.length; i++) {
//data.push({"country":json.observation_location[i].country,"city":json.observation_location[i].city});
var row = Ti.UI.createTableViewRow({
height: 60,
//filter:observation_location[i].
});
var countryLabel = Ti.UI.createLabel({
text: json.current_observation.observation_location.country, //json.observation_location[i].country,
height: 'auto',
left: 10,
top: 5,
});
var cityLabel = Ti.UI.createLabel({
text: json.current_observation.observation_location.city, //json.observation_location[i].city,
height: 'auto',
left: 15,
});
row.add(countryLabel);
row.add(cityLabel);
data.push(row);
//}
tableview.setData(data);
},
onerror: function () {
alert('There was an error retrieving the remote data. Try again.');
}
//timeout:5000
});
xhr.open("GET", "http://api.wunderground.com/api/02e5dd8c34e3e657/geolookup/conditions/forecast/q/Dhaka,Bangladesh.json");
xhr.send();
win.add(tableview);
win.open();