这是我的 iPhone 应用程序中的一个模块。它的目的是从 JSON responeText 返回一个数组,然后可以将其添加到另一个模块中 TableView 的数据属性中。
对于 JavaScript 来说相对较新,我找不到正确的语法来将数组传递给变量 self。
function Events() {
var self = [];
var xhr = Ti.Network.createHTTPClient();
xhr.open('GET', 'http://localhost/ngparser/events.php');
xhr.onload = function() {
var events = JSON.parse(this.responseText),
rows = [];
Ti.API.info('JSON responseText: ');
Ti.API.info(events);
for (var i in events) {
var id = events[i].id,
title = events[i].title;
var amp = title.search('&');
if (amp != -1) {
title = title.replace('&', '&');
}
var row = Ti.UI.createTableViewRow({
title: title,
hasChild: true
});
rows.push(row);
}
// I want this...
return rows;
};
xhr.send();
self = //... to end up here!
self = xhr.send(); //Does not work
return self;
}
module.exports = Events;
编辑:最终在这里找到了解决方案 http://developer.appcelerator.com/question/133913/how-do-i-pass-result-from-xhronload-function-to-variable#comment-119031
最佳答案
xhr.onload 函数是异步运行的,不会返回值,因此返回 rows 变量是没有用的。
您可以做的是在回调函数内使用 TableView 的 setData 方法将行数组添加到 TableView 。
function Events() {
var self = [];
var xhr = Ti.Network.createHTTPClient();
xhr.open('GET', 'http://localhost/ngparser/events.php');
xhr.onload = function() {
var events = JSON.parse(this.responseText),
rows = [];
Ti.API.info('JSON responseText: ');
Ti.API.info(events);
for (var i in events) {
var id = events[i].id,
title = events[i].title;
var amp = title.search('&');
if (amp != -1) {
title = title.replace('&', '&');
}
var row = Ti.UI.createTableViewRow({
title: title,
hasChild: true
});
rows.push(row);
}
tableView.setData(rows);
};
xhr.send();
}
关于javascript - 将 onload 函数的结果传递给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9739141/