[英]Accessing variable outside on load function
嗨,我正在使用Titan Studio開發Android應用程序。我已經開發了一個小型應用程序。我的問題是我無法訪問xhr.on加載中定義的變量,我使用了以下代碼:
xhr.onload = function()
{
var json = this.responseText;
var to_array = JSON.parse(json);
var to_count = to_array.length;
};
我想在onload函數之外訪問to_count和to_array並將其傳遞給另一個子窗口。為此,我使用了以下代碼:
var feedWin = Titanium.UI.createWindow({
url:'home/feed.js'
});//alert(to_count);
feedwin.to_array = to_array;
feedwin.to_count = to_count;
XHR客戶端默認情況下是異步的,這意味着代碼將在XHR運行時繼續執行。 如果您有依賴於XHR完成的代碼,則需要從onload函數中調用該代碼,或者通過在xhr.send()
添加“ false”作為第三個參數來強制XHR同步。 (我發現第一個選擇是更可靠的選擇,並且更符合Titanium期望/感覺的最佳實踐,僅是FYI)。
最好的方法是在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;
};
要么
var feedWin = Titanium.UI.createWindow({
url:'home/feed.js'
});
xhr.onload = function()
{
var json = this.responseText,
feedWin.to_array = JSON.parse(json);
feedWinto_count = to_array.length;
};
我不熟悉Titanium,所以我不知道具體情況,但這是我的最佳猜測。
我對Titanium不太熟悉,但是在聲明范圍內,我認為這是在函數之外使用它們的工作。
var to_array;
var to_count;
xhr.onload = function()
{
var json = this.responseText;
to_array = JSON.parse(json);
to_count = to_array.length;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.