2011-11-06 71 views
0

我在一个函数中创建了一个AJAX请求。但是,我不知道如何返回JSON结果 - 任何人都可以告诉我如何?如何在Sencha Touch中获得服务器JSON响应?

function getData(arg1, arg2, arg3){ 

    Ext.Ajax.request({ 
     url: 'getData.php', 
     params: { 
      arg1: arg1, 
      arg2: arg2, 
      arg3: arg3 
     }, 
     method: 'POST', 
     success: function(response, opts) { 
      var jsonData = Ext.util.JSON.decode(response.responseText); 
      console.log(jsonData); <-- Can see the result here! 
     }, 
     failure: function(response, opts) { 
      console.log('server-side failure with status code ' + response.status); 
     } 
    }); 
    return /jsonData/ <-- Here is the value I want?! 

} 

回答

1

的原因,你的jsonData如果你用它在你的getData功能是不会得到任何信息 - 在成功回调回报(记住,请求是异步) - 该getData范围已经退出。

,你可以和应该做的就是定义一个处理函数:

function handleSuccess(response, opts) 
{ 
    var jsonData = Ext.util.JSON.decode(response.responseText); 
    // use jsonData here in whatever way you please 
} 

然后定义你的getData像这样:

function getData(arg1, arg2, arg3){ 

    Ext.Ajax.request({ 
     url: 'getData.php', 
     params: { 
      arg1: arg1, 
      arg2: arg2, 
      arg3: arg3 
     }, 
     method: 'POST', 
     success: handleSuccess, 
     failure: handleError 
    }); 
    // Note the lack of return statement. 
} 

当然,你可以用你的错误处理相同的:

function handleError(response, opts) 
{ 
    console.log('server-side failure with status code ' + response.status); 
} 

更新

没有办法为你做这样的事情(其中result将得到服务器的响应):

... 
var result = getData('arg1', 'arg2', 'arg3'); 
... 

可靠,还自称的AJAX请求。如果你仔细想想 - 如果有上述可能,它将基本上成为同步请求。

两种方式在jsonData包含服务器响应做你的计算是:

1)做它在handleSuccess功能,并相应地调整你的代码的其余部分(如侧没有 - 你可以通过处理函数作为参数在options.callbackExt.Ajax和)

2)通过常规手段让你的服务器的请求同步(不推荐)

+0

感谢您的快速反应。是的,我理解你的意思,但我的目标是获得从服务器返回的值,并且此值'jsonData'将用于另一个函数进行计算。我怎样才能做到这一点? – hunteryxx

+0

@ user888022查看更新 – ZenMaster

+0

感谢ZenMaster,我真的很感谢你的解释。有没有机会通过使用商店来完成这种任务? – hunteryxx

相关问题