Javascript 访问加载函数外部的变量

Javascript 访问加载函数外部的变量,javascript,android,mobile,titanium-mobile,Javascript,Android,Mobile,Titanium Mobile,您好,我正在使用titanium studio进行Android应用程序开发。我开发了一个小应用程序。我的问题是,我无法访问xhr.on加载中定义的变量。我使用了以下代码: xhr.onload = function() { var json = this.responseText; var to_array = JSON.parse(json); var to_count = to_array.length; }; var feedWin = Titanium.UI.createWindow

您好,我正在使用titanium studio进行Android应用程序开发。我开发了一个小应用程序。我的问题是,我无法访问xhr.on加载中定义的变量。我使用了以下代码:

xhr.onload = function()
{
var json = this.responseText;
var to_array = JSON.parse(json);
var to_count = to_array.length;
};
var feedWin = Titanium.UI.createWindow({
    url:'home/feed.js'
});//alert(to_count);
feedwin.to_array = to_array;
feedwin.to_count = to_count; 
我想访问onload函数外部的\u count和\u array,并将其传递给另一个子窗口。为此,我使用了以下代码:

xhr.onload = function()
{
var json = this.responseText;
var to_array = JSON.parse(json);
var to_count = to_array.length;
};
var feedWin = Titanium.UI.createWindow({
    url:'home/feed.js'
});//alert(to_count);
feedwin.to_array = to_array;
feedwin.to_count = to_count; 

我不太熟悉钛,但请注意声明的范围,我认为这是在函数之外使用它们所需要做的

var to_array;
var to_count;


xhr.onload = function()
{
var json = this.responseText;
to_array = JSON.parse(json);
to_count = to_array.length;
};

我不太熟悉钛,但请注意声明的范围,我认为这是在函数之外使用它们所需要做的

var to_array;
var to_count;


xhr.onload = function()
{
var json = this.responseText;
to_array = JSON.parse(json);
to_count = to_array.length;
};

默认情况下,XHR客户端是非同步的,这意味着代码将在XHR运行时继续执行。如果您有依赖于XHR完成的代码,那么您需要从onload函数中调用该代码,或者通过向XHR添加false作为第三个参数来强制XHR同步。send我发现第一个选项更可靠,并且更符合Tianium的期望/感觉是最佳实践,仅供参考。

默认情况下,XHR客户端是异步的,这意味着代码将在XHR运行时继续执行。如果您有依赖于XHR完成的代码,那么您需要从onload函数中调用该代码,或者通过向XHR添加false作为第三个参数来强制XHR同步。send我发现第一个选项更可靠,并且更符合Tianium的期望/感觉是最佳实践,仅供参考。

实现这一点的最佳方法是在onload中初始化feedWin。因此,以下两个代码段中的一个应该可以工作:

xhr.onload = function()
{
    var json = this.responseText,
        feedWin = Titanium.UI.createWindow({
            url:'home/feed.js'
        });//alert(to_count);

    feedWin.to_array = JSON.parse(json);
    feedWinto_count = to_array.length;
};


我不熟悉钛,所以我不知道细节,但这是我最好的猜测。

实现这一点的最好方法是在onload中初始化feedWin。因此,以下两个代码段中的一个应该可以工作:

xhr.onload = function()
{
    var json = this.responseText,
        feedWin = Titanium.UI.createWindow({
            url:'home/feed.js'
        });//alert(to_count);

    feedWin.to_array = JSON.parse(json);
    feedWinto_count = to_array.length;
};


我不熟悉钛,所以我不知道具体情况,但这是我最好的猜测。

为此,您需要确保调用feedwin.to\u array=to\u array;feedwin.to_count=to_count;在调用onload之后发生。Javascript不像C一样是基于引用的,因此,如果您在加载之前调用过它们,它们将得到null/未定义的值;feedwin.to_count=to_count;在调用onload之后发生。Javascript不像C那样是基于引用的,因此,如果您在加载之前调用过这些函数,它们将得到null/未定义的值。