Home > Web Front-end > JS Tutorial > Example sharing of using when in jQuery to implement multiple AJAX requests corresponding to a single callback_jquery

Example sharing of using when in jQuery to implement multiple AJAX requests corresponding to a single callback_jquery

WBOY
Release: 2016-05-16 16:51:27
Original
1231 people have browsed it

I know that these functions are executed asynchronously (asyncronously) and will return with a delay, so I want to know if there is a way that I can use a single callback to load them in parallel, just like the JS loader curljs does That way. Lucky me! With jQuery.when, I can load two requests concurrently and only execute the callback once!

jQuery Script
As I mentioned, here is a use case for loading a script and a JSON resource:

Copy Code The code is as follows:

$.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 you can also use ".done"
// Yay, loading is complete, we can perform some dependency operations here.
});

When the resource loading is completed, the specified done or then callback will be triggered, so you can know that the request has been completed. The type of callback parameter object returned by each request is different, so the above request may return the following information:

Copy code The code is as follows:

// Format: [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 still need to add a traditional AJAX XHR request, such as a widget template, we can do this:

Copy code The code is as follows:

$.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);
});

Dojo Toolkit has had this kind of functionality for a long time, but I’m quite excited that jQuery can do it too. For current development, it is a natural requirement for multiple requests that are not synchronized and whose return order is uncertain to share the same callback, so jQuery is definitely advancing with the times!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template