javascript - 将 onload 函数的结果传递给变量

标签 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.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/

相关文章:

javascript - 我的 ng-click 和 ng-if 在托管后不起作用

javascript - 防止同一函数触发两次

javascript - 将毫秒转换为本地时间和日期 javascript

mysql - Node.js脚本通过socket.io连接MySQL数据库

ios - 从 Titanium 中的 UTC 时间获取设备时间/本地时间

javascript - 使用promise的resolve数据改变变量的值

javascript - 为什么在reactjs中使用JSON.parse会导致跨源错误?

titanium - 为什么钛合金的构建过程如此缓慢?

model - 无法在 Titanium Appcelerator 中使用合金更新模型

javascript - 创建特定 View 的模式