Ajax 链式回调
我的网站上有一个导航栏,它是在某个链中构建的:
// in Init method
nav
.hideContainer()
.fetchData()
.buildHTML()
.eventify()
.showContainer();
没关系,并且对我来说工作得很好。但在 fetchData 方法中,我使用本地数据来加载(内联 json)。但现在,我需要获取远程数据(来自 ajax 调用)。我可以在不更改 Init
方法的情况下完成它吗?
我尝试通过同步 ajax 调用来做到这一点:
// in fetchData() method
var data;
$.ajax ({
async: false,
url : '/some/url/',
success : function(res) {
data = res;
}
});
return data;
但我知道,它很慢 - 它在加载时阻塞浏览器。
我知道,我可以修改我的 Init
方法,就像这样:
nav
.hideContainer()
.fetchData(function(){
nav.buildHTML().eventify().showContainer()
});
但是,我不想修改 Init
方法,我可以这样做吗?
PS 我认为我应该朝 Deffered
对象的方向发展。我说得对吗?
I'm having a navigation bar on my site, and it's being built in some chain:
// in Init method
nav
.hideContainer()
.fetchData()
.buildHTML()
.eventify()
.showContainer();
It's OK, and works fine for me. But in fetchData
method I use local data to load ( inline json). But now, I need to get remote data (from an ajax calling). Can I make it without changing Init
method?
I had an attempt to do this with an synchronous ajax call:
// in fetchData() method
var data;
$.ajax ({
async: false,
url : '/some/url/',
success : function(res) {
data = res;
}
});
return data;
But I know, that it's slow - it's blocking the browser while it's loading.
I know, that I can modify my Init
method, like in a such way:
nav
.hideContainer()
.fetchData(function(){
nav.buildHTML().eventify().showContainer()
});
But, I'd like not to modify Init
method, can I do this?
P.S. I think I should go in direction of Deffered
object. Am I right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能让
$.ajax
异步工作,同时又期望.fetchData()
返回您的数据。您是对的,设置
async: false
是不好的,而更改init()
是更好的选择,即使您失去了优雅的链接。您可以这样更改代码:
您不必在
fetchData()
函数中引入回调,因为您可以返回 延迟对象由ajax()
返回,然后调用done()
- 参见文档。另请参阅 fail() 和 then() 如果你想处理错误。
You cannot have
$.ajax
working asynchronously and at the same time expect.fetchData()
to return with your data.You are right that setting
async: false
is bad and changing theinit()
is a better alternative even when you lose elegant chaining.You can change your code like this:
You don't have to introduce callbacks into
fetchData()
function, because you can return deferred object returned byajax()
and then calldone()
on it - see documentation.See also fail() and then() if you want to handle errors.
在 fetch 方法中执行类似的操作
然后,当数据传入时,它将调用 buildHTML()
Do something like this in your fetch Method
Then, when the data comes in, it will call buildHTML()