等到所有 jQuery Ajax 请求完成?

编程入门 行业动态 更新时间:2024-10-25 03:28:47
本文介绍了等到所有 jQuery Ajax 请求完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何让一个函数等到所有 jQuery Ajax 请求在另一个函数内完成?

How do I make a function wait until all jQuery Ajax requests are done inside another function?

简而言之,在执行下一个请求之前,我需要等待所有 Ajax 请求完成.但是如何?

In short, I need to wait for all Ajax requests to be done before I execute the next. But how?

推荐答案

jQuery 现在定义了一个 when 函数 为此目的.

jQuery now defines a when function for this purpose.

它接受任意数量的 Deferred 对象作为参数,并在它们全部解析时执行一个函数.

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

这意味着,如果你想发起(例如)四个 ajax 请求,然后在它们完成后执行一个操作,你可以这样做:

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){ // the code here will be executed when all four ajax requests resolve. // a1, a2, a3 and a4 are lists of length 3 containing the response text, // status, and jqXHR object for each of the four ajax calls respectively. }); function ajax1() { // NOTE: This function must return the value // from calling the $.ajax() method. return $.ajax({ url: "someUrl", dataType: "json", data: yourJsonData, ... }); }

在我看来,它提供了干净清晰的语法,并避免了涉及任何全局变量,例如 ajaxStart 和 ajaxStop,这可能会在您的页面开发过程中产生不必要的副作用.

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.

如果你事先不知道你需要等待多少个ajax参数(即你想使用可变数量的参数),它仍然可以完成,但只是有点棘手.请参阅将延迟数组传递给 $.when()(可能还有 jQuery .when 使用可变数量的参数进行故障排除).

If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).

如果您需要更深入地控制 ajax 脚本等的失败模式,您可以保存 .when() 返回的对象 - 它是一个 jQuery Promise 对象包含所有原始 ajax 查询.您可以在其上调用 .then() 或 .fail() 以添加详细的成功/失败处理程序.

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

更多推荐

等到所有 jQuery Ajax 请求完成?

本文发布于:2023-11-26 16:49:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:jQuery   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!