Jquery Ajax beforeSend and success,error & complete

后端 未结 2 1066
小鲜肉
小鲜肉 2020-12-01 02:19

I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 02:39

    Maybe you can try the following :

    var i = 0;
    function AjaxSendForm(url, placeholder, form, append) {
    var data = $(form).serialize();
    append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        beforeSend: function() {
            // setting a timeout
            $(placeholder).addClass('loading');
            i++;
        },
        success: function(data) {
            if (append) {
                $(placeholder).append(data);
            } else {
                $(placeholder).html(data);
            }
        },
        error: function(xhr) { // if error occured
            alert("Error occured.please try again");
            $(placeholder).append(xhr.statusText + xhr.responseText);
            $(placeholder).removeClass('loading');
        },
        complete: function() {
            i--;
            if (i <= 0) {
                $(placeholder).removeClass('loading');
            }
        },
        dataType: 'html'
    });
    }
    

    This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

    I cannot test it, let me know if it works or not.

提交回复
热议问题