Appcelerator:可变范围问题

时间:2011-04-17 12:36:18

标签: javascript appcelerator-mobile

我在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();
     }
}

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

2 个答案:

答案 0 :(得分: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();
     }
}

答案 1 :(得分:0)

尝试“data = c.responseData”而不是“data = this.responseData”。只是基于this ......

的疯狂猜测