简体   繁体   English

如何从Javascript同步运行Ajax函数?

[英]How can I run Ajax functions synchronously from Javascript?

I have the following code: 我有以下代码:

$('#DoButton').click(function (event) {
  event.preventDefault();
  $("input:checked").each(function () {
    var id = $(this).attr("id");
    $("#rdy_msg").text("Starting" + id);
    doAction(id);
  });
});

function doAction(id) {
            var parms = { Id: id };
            $.ajax({
                type: "POST",
                traditional: true,
                url: '/adminTask/doAction',
                async: false,
                data: parms,
                dataType: "json",
                success: function (data) {
                    $("#rdy_msg").text("Completed: " + id);
                },
                error: function () {
                    var cdefg = data;
                }
            });
        }

When the button is clicked it checks the form and for each checked input it calls doAction() which then calls an Ajax function. 单击该按钮时,它将检查表单,并为每个检查的输入调用doAction(),然后再调用Ajax函数。 I would like to make it all synchronous with a 2 second delay between the completion of one call and the running of the next. 我希望在一次通话完成与下一次通话之间有2秒的延迟,以使其全部同步。 The delay is to give the user time to see that the last action has completed. 延迟是为了让用户有时间看到上一个动作已完成。

By setting async=false will that really make the ajax function wait? 通过设置async = false,这真的会使ajax函数等待吗?

How can I add a 2 second wait after the Ajax has run and before the next call to doAction? 如何在Ajax运行之后和下一次调用doAction之前添加2秒的等待时间?

There is option in jQuery to set the ajax function synchronous jQuery中有一个选项可以将ajax函数设置为同步

$.ajaxSetup({
   async: false
});

To make the function to wait you can use .delay() 要使函数等待,可以使用.delay()

Try the solution of this question also. 也尝试这个问题的解决方案。

将setTimeout用于AJAX调用doAction。

Try to do it using recursion 尝试使用递归做到这一点

$('#DoButton').click(function (event) {
  event.preventDefault();
  doAction( $("input:checked").toArray().reverse() );
});

function doAction(arr) {
    if( arr.length == 0 ) return;

    var id = arr.pop().id;
    $("#rdy_msg").text("Starting" + id);
    $.ajax({
        type: "POST",
        traditional: true,
        url: '/adminTask/doAction',
        async: false,
        data: { Id: id },
        dataType: "json",
        success: function (data) {
            $("#rdy_msg").text("Completed: " + id);
            setTimeout(function(){ doAction(arr); }, 2000);
        },
        error: function () {
            var cdefg = data;
            $("#rdy_msg").text("Error: " + id);
            setTimeout(function(){ doAction(arr); }, 2000);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM