[英]Can't parse JSON Object, Stringify or get javascript property
[英]Can't get JSON file to parse into TableView in JavaScript using Appcelerator
我正在尝试使用Appcelerator将JSON文件放入JavaScript的表中,但我不确定为什么在编译为示例页面时为什么将其输出为空表。 我对JavaScript和JSON格式都比较陌生,因此,如果您发现任何愚蠢的逻辑或语法错误,请放轻松,并让我知道如何解决此问题:
// Set the background color with no windows or tabs
Titanium.UI.setBackgroundColor('#000');
// Create the window
var win1 = Titanium.UI.createWindow({
title:'Challenge Window',
backgroundColor:'#fff',
});
// Store the image and its properties
var image = Titanium.UI.createImageView({
image: "https://myavantiservices.files.wordpress.com/2015/02/helloworld.gif",
height: 380,
width: 380,
center: 512,
top: -50
});
var tableData;
// Parse our JSON file using onload
var url = "https://www.sitepoint.com/twitter-json-example/";
var json;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
json = JSON.parse(this.responseText);
tableData = json;
}
});
// Create the table and insert the JSON data
var table = Titanium.UI.createTableView({
data: tableData,
height: 480,
width: 480,
top: 256,
left: 232
});
// Add the image to the window and open the window
win1.add(image);
win1.add(table);
win1.open();
网址返回的JSON:
{"results":[
{"text":"@twitterapi https://code.google.com/archive/p/twitter-api/issues/353",
"to_user_id":396524,
"to_user":"TwitterAPI",
"from_user":"jkoum",
"metadata":
{
"result_type":"popular",
"recent_retweets": 109
},
"id":1478555574,
"from_user_id":1833773,
"iso_language_code":"nl",
"source":"twitter< /a>",
"profile_image_url":"http://s3.amazonaws.com/twitter_production/profile_images/118412707/2522215727_a5f07da155_b_normal.jpg",
"created_at":"Wed, 08 Apr 2009 19:22:10 +0000"},
... truncated ...],
"since_id":0,
"max_id":1480307926,
"refresh_url":"?since_id=1480307926&q=%40twitterapi",
"results_per_page":15,
"next_page":"?page=2&max_id=1480307926&q=%40twitterapi",
"completed_in":0.031704,
"page":1,
"query":"%40twitterapi"}
}
您需要将所有依赖于JSON响应的内容移到onload
块中。 否则,将在tableData
具有任何数据之前构造表。 您实际上也没有发送xhr
。
一旦获得实际返回该JSON的URL,就可以使用以下代码:
var url = "https://www.sitepoint.com/twitter-json-example/";
var json;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
json = JSON.parse(this.responseText);
tableData = json;
var table = Titanium.UI.createTableView({
data: tableData,
height: 480,
width: 480,
top: 256,
left: 232
});
win1.add(image);
win1.add(table);
win1.open();
}
});
xhr.open("GET", url);
xhr.send();
Jodo,您确实需要阅读有关在TableView上使用HTTP Client和Set Data的文档。
Titanium使用远程数据的文档中有一个非常干净的示例
您使用的url除了返回该网站的HTML输出外没有返回其他任何内容,其次,您不能简单地在tableview上设置data属性,除非以这种方式之一格式化数据变量。
[ {title: 'Apples'}, {title: 'Bananas'}, {title: 'Carrots'}, {title: 'Potatoes'} ];
而且,TableView的data属性采用行/部分数组或格式良好的字典。 看到更多的TableView指南
如果您以前从未尝试过任何操作,建议您先阅读文档。 它将帮助您更好地学习和理解,并且肯定会节省您的宝贵时间。 :) 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.