简体   繁体   中英

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. 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. 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?

How can I add a 2 second wait after the Ajax has run and before the next call to doAction?

There is option in jQuery to set the ajax function synchronous

$.ajaxSetup({
   async: false
});

To make the function to wait you can use .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);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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