等到所有ajax请求完成

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

我需要等到我的所有ajax功能都完成,然后继续执行exectution。

I need to wait until all my ajax functions are done, and then continue the exectution.

我的特殊情况是我需要翻译表单中的某些字段在提交之前。我通过对外部站点的ajax调用来翻译它们。根据表单中的某些值,我需要做更多或更少的翻译。完成所有翻译后(如果有的话)我必须用ajax验证表单,如果有效,则提交。

My particular case is that I need to translate some fields in a form before submitting it. I translate them with an ajax call to an external site. Depending on some values in the form i would need to do more or less translations. When all the translations are done (if any) I have to validate the form with ajax, and if its valid, then submit.

这是我的方法: 首先,我有一个函数发送ajax调用并对收到的数据做一些事情:

This is my aproach: First, I have a function that sends the ajax call and do stuff with the data received:

function translate(...) { $("#ajaxCounter").val(parseInt($("#ajaxCounter").val()) + 1); $.ajax({ ... success:function(data) { ... $("#ajacCounter").val(parseInt($("#ajaxCounter").val()) - 1); } });

然后,当要提交表单时,我执行以下代码:

Then, when the form is to be submitted I execute the following code:

$("#form").submit(function() { translatable_fields.each(function() { translate(...); }); while (parseInt($("#ajaxCounter").val()) > 0) { null; } if (!(this).hasClass('ready')) { $.ajax({ //validation success: function(data) { if (data['isValid']) { $("#form").addClass('ready'); $("#form").submit(); } } }); } return true; });

问题是而循环提交函数永远不会结束。

The problem is that the while loop in the submit function never ends.

如果我在没有的情况下执行代码,而循环我可以看到 ajaxCounter 输入在翻译函数开始时增加,在结束时减少。

If I execute the code without the while loop I can see the ajaxCounter input increasing when the translation functions start and decreasing when they end.

推荐答案

你可以使用从 $。ajax 调用返回的 deferred 对象以更整洁的方式实现此目的。首先你应该得到 translate()函数来返回 deferred :

You can achieve this in a much neater fashion using the deferred objects returned from a $.ajax call. First you should get the translate() function to return the deferred:

function translate(...){ return $.ajax({ // settings... }); });

然后你可以把所有这些承诺放到一个数组中:

Then you can put all those promises in to a single array:

var requests = []; translatable_fields.each(function(){ requests.push(translate(...)); });

然后你可以将该数组应用于 $。当:

Then you can apply that array to $.when:

$.when.apply($, requests).done(function(schemas) { console.log("All requests complete"); // do something... });

更多推荐

等到所有ajax请求完成

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

发布评论

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

>www.elefans.com

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