0

我在 Titanium Appcelerator 中使用以下代码连接远程主机:

var connect_remote = function(url)
{
    /*
     * make sure that the Device is connected before initiate process as we don't want to force
     * the user to open remote stream just for sake of new entries
     */
     //alert("In Func" + is_connected());
     var d_data = null;
     if(is_connected())
     {

         var c = Titanium.Network.createHTTPClient();
         var data = null;
         c.setTimeout(10000);
         c.onload = function()
            {
                if (c.status == 200 )
                {
                    data = this.responseData;
                    Titanium.App.Properties.setString('returnData',data);
                }
            };

        c.error = function(e)
        {
            alert("Error = "+e.error);
        }
        c.open('GET',url);
        c.send();
     }
}

我想返回应该保留响应值的数据变量的值,以便我可以使用,但它总是返回 null 或未定义。如何从中返回值数据

4

2 回答 2

1

您的意思并不完全清楚,但我认为您希望您的“connect_remote()”函数向您返回一些值。你不能在像你这样的异步环境中这样做。相反,您可以将一个函数传递给“connect_remote()”,当“onload”处理程序运行时,该函数可以传递“data”值。

var connect_remote = function(url, handler)
{
    /*
     * make sure that the Device is connected before initiate process as we don't want to force
     * the user to open remote stream just for sake of new entries
     */
     //alert("In Func" + is_connected());
     var d_data = null;
     if(is_connected())
     {

         var c = Titanium.Network.createHTTPClient();
         var data = null;
         c.setTimeout(10000);
         c.onload = function()
            {
                if (c.status == 200 )
                {
                    data = this.responseData;
                    Titanium.App.Properties.setString('returnData',data);
                    handler(data);
                }
            };

        c.error = function(e)
        {
            alert("Error = "+e.error);
        }
            c.open('GET',url);
        c.send();
     }
}
于 2011-04-17T13:09:43.287 回答
0

尝试“data = c.responseData”而不是“data = this.responseData”。只是基于的疯狂猜测...

于 2011-04-17T13:09:32.193 回答