从 JSONP 回调返回数据
我有一个获取 jsonp 数据的类。我想简单地返回一个值,但无法这样做。回调不会更新类属性 - 不确定这是时间问题还是范围问题
Ext.define("App.ContentManager", {
extend: "Ext.util.Observable",
singleton: true,
data: 'empty',
getData: function() {
this.doLoad();
console.log(a.data) //not correct - shows original value
return this.data;
},
doLoad: function(url) {
var a = this;
Ext.util.JSONP.request({
url: "http://example.com/somejson",
callbackKey: "callback",
callback: function(c) {
a.data = c;
console.log(a.data) //correct json data is here
}
})
},
});
I have a class that fetches jsonp data. I would like to simply return a value but am unable to do so. The callback does not update the class property - not sure if it is a timing or scope issue
Ext.define("App.ContentManager", {
extend: "Ext.util.Observable",
singleton: true,
data: 'empty',
getData: function() {
this.doLoad();
console.log(a.data) //not correct - shows original value
return this.data;
},
doLoad: function(url) {
var a = this;
Ext.util.JSONP.request({
url: "http://example.com/somejson",
callbackKey: "callback",
callback: function(c) {
a.data = c;
console.log(a.data) //correct json data is here
}
})
},
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然是时间问题。使用
getDate
函数中的doLoad()
,您只需启动请求,而无需等待它完成才能在下一行中准备好数据。您只需在doLoad
方法的callback: function
中准备好数据。因此,无论您需要做什么,最好在一个函数中发送请求,然后在callback:function
中设置一个将使用返回数据的函数。更新
另外我刚刚注意到还有一个范围问题。您可以通过添加 a 在 JSONP 请求中传递范围
,然后在 getDate 中您应该:
this.data
因为a
是doLoad方法。
Of course is timing issue. With
doLoad()
in thegetDate
function you just start the request and you don't wait for it to complete in order to have the data ready in the next line. You only have the data ready in thecallback: function
of thedoLoad
method. So whatever you need to do it's best to send the request in one function and then in thecallback:function
have a function that will use the data returned.Update
Also I just noticed is a scope issue too. You shout pass the scope in the JSONP request with adding a
And then in the getDate you should:
this.data
sincea
is local variable in thedoLoad
method.正如现有注释中所述,由于
doLoad
方法异步检索数据,因此无法直接从方法调用返回结果。您的两个选择是:或者你甚至可以两者都做(未经测试):
As noted in existing comments, since the
doLoad
method retrieves the data asynchronously, there is no way to return the result directly from the method call. Your two options would be:Or you could even do both (untested):