如何在Sencha Touch中获取服务器JSON响应

How to get the server JSON response in Sencha Touch?

本文关键字:获取 服务器 JSON 响应 Touch Sencha      更新时间:2023-09-26

我在一个函数中创建了一个AJAX请求。然而,我不确定如何返回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?!
}

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

你可以而且应该做的是定义一个handler函数:

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)

使您的服务器请求同步(不可取)通过通常的方法