我正在使用 Titanium SDK 开发一个与远程 PHP 文件交互以检索其数据的小型 Android 应用程序。 FOR 循环在 HTTPClient 返回任何数据之前执行,因此“myTest”为空并且没有任何内容添加到“tblListing”。
function jsonPOST( inAction, inParams ) { // jsonPOST is a global function
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
return this.responseText;
},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
return false;
},
timeout : 8000, // in milliseconds
});
var sendData = {
'action' : inAction,
'json' : JSON.stringify(inParams)
};
xhr.open('POST', "http://domain.com/file.php"); // url redacted
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send( sendData );
} // end. jsonPOST()
var myTest = jsonPOST('getlisting'); // only need to pass first param in this instance
for (i in myTest) {
tblListing.appendRow({ title: myTest[i].title, id: myTest[i].id });
}
在不延迟同一线程上其他任何事情的执行的情况下,如何让 FOR 循环等待 HTTPClient 返回数据? “jsonPOST”函数用于检索应用中多个元素的各种数据,并且应该保持动态。
最佳答案
我最终使用回调参数允许在 HTTPClient 接收到数据后调用函数。这允许 jsonPOST 函数保持动态。
function jsonPOST(inAction, inParams, inCallback) {
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
var reply = JSON.parse(this.responseText);
inCallback(reply);
},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
return false;
},
timeout : 8000, // in milliseconds
});
var sendData = {
'action' : inAction,
'json' : JSON.stringify(inParams)
};
xhr.open('POST', "http://domain.com/file.php"); // url redacted
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(sendData);
}
function processListing(inJson) {
for (i in inJson) {
tblListing.appendRow({
title : inJson[i].listingTitle,
id : inJson[i].listingID
});
}
}
jsonPOST('getListing', null, processListing);
关于android - Titanium,等待 HTTPClient 回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19443824/