简体   繁体   中英

ajax request modal ordering with bootstrap

I want to use modal window globally in my app, so set up on jquery's ajax complete and ajax start configurations. I am having an issue where modal windows called from within the ajax success callbacks are conflicting with my ajax notification modal, because they are not executing in the order I want.

In this demo, I want it to alert 1 then 2 then 3, but it is executing the success handler first...

http://jsfiddle.net/AsRxL/

$(document).ajaxStart(function(){
    alert("1")
    $("#first").modal("show")
})
$(document).ajaxComplete(function(){
    alert("2")
    $("#first").modal("hide")
})

$.get('./',function(d, e){
    alert("3")
    // now the problem is the previous modal has not
    // yet fully dismissed
    $("#second").modal("show")
})

How can I get the ajaxComplete function to fire, and remove my notification modal before any callback functions are executed, which might themselves create modal windows?

The reason why they are not executing in order you want is in jQuery docs ( http://api.jquery.com/ajaxComplete/ , http://api.jquery.com/ajaxStart/ )

AjaxStart event triggers BEFORE your ajax request implementation.

AjaxComplete event triggers AFTER your ajax done implementation.

$(document).ajaxStart(function(){
    alert("AjaxStart");
});

$(document).ajaxComplete(function(){
    alert("AjaxComplete");
});

$.get('./',function(d, e){
    alert("Get A Start")
}).done(function(){
    alert("Get A Done");
});

$.get('./',function(d, e){
    alert("Get B Start")
}).done(function(){
    alert("Get B Done");
});

So if you run this fiddle ( http://jsfiddle.net/KbzCk/ ) you will see the correct order of execution.

If you are using bootstrap 3 modal, try checking Events section

$('#modal-id').on('hidden.bs.modal', function () {
    //show another modal
})

Even though, showing so many modal windows does not seem like good approach.

If you are using modal just for notifications, try using toastr: http://www.johnpapa.net/toastr100beta/

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