Javascript 将结果从onload函数传递给变量

Javascript 将结果从onload函数传递给变量,javascript,titanium,titanium-mobile,Javascript,Titanium,Titanium Mobile,这是我iPhone应用程序中的一个模块。它的目的是从JSON responeText返回一个数组,然后可以将该数组添加到另一个模块中TableView的数据属性中 由于对JavaScript比较陌生,我无法找到将数组传递给变量self的正确语法 function Events() { var self = []; var xhr = Ti.Network.createHTTPClient(); xhr.open('GET', 'http://localhost/ngparser/events.

这是我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;

编辑:最终在这里找到了一个解决方案,AJAX是异步的,
onload
函数在AJAX调用完成时运行。这意味着JavaScript将继续执行您的函数,并在以后运行
onload
。这意味着您不能从中返回值


您需要将与
(或
self
)变量相关的所有代码放入
onload
函数中。

xhr.onload函数是异步运行的,不会返回值,因此返回rows变量是无用的

您可以在回调函数中使用表视图的setData方法将行数组添加到表视图中

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

我一直在玩回调,但无法让它工作。我的EventScalBack似乎没有运行,因为info()没有输出。窗口模块:数据模块:如果onload回调没有启动,那么肯定有错误。尝试将info()添加到onerror回调中,看看是否触发了。xhr.onload in Events()是否确实触发了,因为我从函数中的info()获得了输出,我是指EventsWindow中的eventsCallback()。很抱歉。我在Events()中添加了“xhr.onerror=function(e){Ti.API.info(e.error);}”,控制台中没有错误。