android - Titanium,等待 HTTPClient 回复

标签 android titanium httpclient

我正在使用 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/

相关文章:

android - 火力地堡安卓 : Retrieve post from current user's friends only

javascript - Titanium Studio 标题导航栏

android - 无法使用 HttpClient 从 Android 设备相机发布图像

Android HttpPost 请求不发布

来自数组值的 Javascript 动态变量名称 (Appcelerator Titanium)

.net-core - 如何在 .NET Core 3 中不使用 RestSharp 代理

Android gradle 测试任务

android - 带有字体标签的字符串资源不起作用

android - 如何找到小部件的默认样式(即 AppCompatEditText)

android - 为钛移动开发禁用双击缩放 WebView