jQuery:多个AJAX和JSON请求,一个回调

I've been working on a new feature for the Mozilla Developer Network which requires loading of a basic script file as well as a JSON stream.  Since we use jQuery, that means a jQuery.getScript and a jQuery.getJSON.  I know those both work asynchronously and return a Deferred, so I wondered if there was a way that I could load them in parallel with one callback, much the way JavaScript loaders like curljs do.  I was in luck!  Using jQuery.when, I can load both requests concurrently with one callback!

我一直在为Mozilla开发人员网络开发一项新功能,该功能需要加载基本脚本文件以及JSON流。 由于我们使用jQuery,因此意味着jQuery.getScriptjQuery.getJSON 。 我知道它们都异步工作并返回Deferred,所以我想知道是否有一种方法可以与一个回调并行地加载它们,就像curl加载器一样。 我很幸运! 使用jQuery.when ,我可以通过一个回调同时加载两个请求!

jQuery JavaScript (The jQuery JavaScript)

As I mentioned, my use case was loading a script and a JSON resource, so how it works is:

正如我提到的,我的用例是加载脚本和JSON资源,因此其工作方式是:


$.when(
	$.getScript('/media/js/wiki-min.js?build=21eb633'), 
	$.getJSON('https://developer.mozilla.org/en-US/demos/feeds/json/featured/')
).then(function(a, b) {  // or ".done"
	
	// Yay, stuff loaded and now we can do something!

});


When the resources are done loading, the done or then callback fires and I know the requests are complete.  Each request type provides a different callback argument object, so the above would provide:

当资源加载完成,在donethen回调火灾,我知道的要求是完整的。 每种请求类型都提供一个不同的回调参数对象,因此上述内容将提供:


// [response, state, jqxhr], [response, state, jqxhr]
["(function(c){var e=c(".from-search-navigate");if(e…;if(j){g.apply(m,l)}}}})(window,document,jQuery);", "success", Object]
[Array[15], "success", Object]


If we wanted to add a traditional AJAX XHR request to the mix, say a widget template, we could do that too:

如果我们想向混合中添加传统的AJAX XHR请求,例如一个小部件模板,我们也可以这样做:


$.when(
	$.getScript('/media/js/wiki-min.js?build=21eb633'), 
	$.getJSON('https://developer.mozilla.org/en-US/demos/feeds/json/featured/'), 
	$.get('/')
).then(function(a, b, c) { 
	console.log(a, b, c); 
});


The Dojo Toolkit has had this type of functionality for a long time but I'm stoked that modern jQuery allows for the same.  Making multiple requests with one callback seems as relevant as any other task these days, so jQuery's definitely moving with the times!

Dojo Toolkit拥有这种功能已经很长时间了,但是我很高兴现代jQuery允许相同的功能。 如今,使用一个回调发出多个请求似乎与其他任何任务都相关,因此jQuery肯定与时俱进!

翻译自: https://davidwalsh.name/jquery-ajax-callback

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值