![](/img/trans.png)
[英]Sencha Touch : How to get the simple json file as response using JSONP?
[英]How to get the server JSON response in Sencha Touch?
我已经在一个函数中创建了一个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
范围已经退出。
您可以并且应该做的是定义一个处理函数:
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.callback
和中将处理函数作为参数传递给Ext.Ajax
)
2)通过常规方式使服务器请求同步(不建议)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.