Fancybox not closing after ajax call

久未见 提交于 2019-12-10 22:44:40

问题


I'm having trouble closing my fancy box in some cases after an ajax call.

 $(document).ajaxStop(function() {
    function(){$.fancybox.close()};
 });

 $(document).ajaxStart(function() {
    $("a#load_gif").trigger('click');
 });

Here's my code handling the fancy box. So my problem is that if the ajax call is very brief and fast the box doesn't close, however if the call is longer it closes automatically as it should.

I have found a fix which goes along the line of this

$(document).ajaxStop(function() {
    setTimeout(function(){$.fancybox.close()},500);
});

But honestly that solution is not good looking. What can I do to make the fancy box close even if the ajax call is returned very fast? The length of the ajax call is variable depending on the number of rows it has to fetch.

Any help and/or suggestions are appreciated.


回答1:


It seems like you have a race condition and maybe the fancybox isn't finished being created and doesn't have it's close function defined yet when your AJAX call is attempting to fire off that close function.

I recommend a 2 step process that triggers the fancybox to close. Create 2 global variables ajaxStop = false; and fancyboxDone = false;

create a function like:

function closeFancyBox(){
    if(ajaxStop && fancyboxDone){
        $.fancybox.close();
        ajaxStop = fancyboxDone = false;
    }
}

Then change your ajax stop to :

 $(document).ajaxStop(function() {
    function(){
      ajaxStop = true;
      closeFancyBox()
    };
 });

And finally add an onComplete function to your fancybox that does the same as the ajax Stop but sets fancyboxDone = true instead of ajaxStop.

So now no matter which one finishes first and second they will be able to check on each other's status and fire the close appropriately.



来源:https://stackoverflow.com/questions/15688176/fancybox-not-closing-after-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!