在 each() 函数内进行多次 ajax 调用.然后在所有调用都完成后做些什么? [英] Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?

查看:26
本文介绍了在 each() 函数内进行多次 ajax 调用.然后在所有调用都完成后做些什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我稍微解释一下我的代码(如果有问题请见谅,我刚刚从头开始编写这个示例,它与我目前拥有的非常接近).

Let me explain my code a little bit (Excuse me if somethings wrong, I've just written this example from scratch, it is very close to what I currently have).

HTML:

<form id="form">
    <!-- Friend 1 -->
    Name 1: <input type="text" name="friendName1" id="friendName1" class="friendName" value=""><br />
    Email 1: <input type="text" name="friendEmail1" id="friendEmail1" value=""><br /><br />
    <!-- Friend 2 -->
    Name 2:<input type="text" name="friendName2" id="friendName2" class="friendName" value=""><br />
    Email 2:<input type="text" name="friendEmail2" id="friendEmail2" value=""><br /><br />
    <!-- Friend 3 -->
    Name 3:<input type="text" name="friendName3" id="friendName3" class="friendName" value=""><br />
    Email 3:<input type="text" name="friendEmail3" id="friendEmail3" value=""><br /><br />
    <!-- Friend 4 -->
    Name 4:<input type="text" name="friendName4" id="friendName4" class="friendName" value=""><br />
    Email 4:<input type="text" name="friendEmail4" id="friendEmail4" value=""><br /><br />
    <!-- Submit -->
    <input name="submit" type="submit" value="Submit">
</form>

JS:

$("#form").submit(function(){

    $(".friendName[value!='']").each(function(){
        var idEmail = 'friendEmail' + $(this).attr("id").replace('friendName','');
        if($("#"+idEmail+"[value!='']").length > 0){
            var name = $(this).val();
            var email = $("#"+idEmail).val();

            // Submit the ajax request
            $.ajax({ 
                type: 'POST', 
                url: 'ajax/url', 
                data: {
                    name: name,
                    email: email
                },
                success: function(json) {
                    // Log a console entry if our ajax request was successful
                    console.log(name + " was submitted via ajax");
                }
            });
        }
    });

    // Redirect the user to the thank you page
    setTimeout( function() { window.location= '/thanks'; }, 2000 );

});

JSFiddle(重定向删除,ajax 调用替换为 fiddle 的控制台日志)

JSFiddle (redirect removed and ajax call replaced with console log for fiddle)

http://jsfiddle.net/cM5PX/

HTML 是一个简单的表单,包含朋友姓名和朋友电子邮件输入字段.

The HTML is a simple form, with friend name and friend email input fields.

JS 有一个 each 函数,如果名称和关联的电子邮件有值,它就会运行一个 ajax 调用.

The JS has an each function, which if the name and associated email have values, it runs an ajax call.

我需要一种方法来运行这些 ajax 调用(可能有 1 个循环,可能有 15 个),然后在它们全部完成后,重定向到新页面.

I need a way for these ajax calls to run (there could be 1 loop, there could be 15) and then after they have all finished, redirect to a new page.

我目前的做法很糟糕,因为所有的 ajax 调用都没有在页面重定向之前完成运行.

The current way I'm doing it is horrible, as all of the ajax calls do not finish running before the page redirects.

我该怎么做才能让它变得更好?它需要万无一失,并且仅在所有 ajax 调用完成后才重定向(成功或错误,无关紧要 - 只需在完成后重定向即可).

What can I do to make this better? It needs to be fool proof and ONLY redirect once all of the ajax calls have finished (success or error, it doesn't matter - it just needs to redirect once its finished).

我尝试过使用 async: false 但它似乎没有什么区别.

I have tried using async: false but it doesn't seem to make a difference.

我想过在 each 函数中放置一个计数器,在 ajax 成功函数中放置一个计数器,如果它们都匹配,则执行重定向,但我正在寻找一些更有经验的指导.

I've thought about putting a counter in the each function and a counter in the ajax success function and if they both match, then do the redirect, but I am looking for some more experienced guidance.

推荐答案

使用 延迟对象:

$("#form").submit(function(e){

    e.preventDefault();

    var calls = [];

    $(".friendName[value!='']").each(function(){
        // Submit the ajax request
        calls.push($.ajax({ 
            type: 'POST', 
            url: 'ajax/url', 
            data: {
                name: name,
                email: email
             },
             success: function(json) {
                // Log a console entry if our ajax request was successful
                console.log(name + " was submitted via ajax");
             }
         }));
    });

    $.when.apply($, calls).then(function() {
        window.location= '/thanks';
    });
});

这篇关于在 each() 函数内进行多次 ajax 调用.然后在所有调用都完成后做些什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆