Spinner bound to ajax call will not display unless I put an alert in the javascript

偶尔善良 提交于 2021-02-20 02:17:45

问题


I wrote a simple method that adds a spinner to the main body of an html page and binds the event to an ajaxstart method then removes it on the ajaxstop.

StartAjaxCallSpinner = function (spinnerObj) {    
    var $bod = $("Body");
    if ($('#bgSpinnerDiv')[0] == undefined && $('#spinnerHolder')[0] == undefined) {
        $bod.append("<div id='spinnerHolder' style='display:none;'></div><div id='bgSpinnerDiv'></div>");
    }

    $('#spinnerHolder')
            .hide()  
            .ajaxStart(function () {
                $('#bgSpinnerDiv').css({ 'background-color': 'black',
                    'height': '100%',
                    'left': '0px',
                    'opacity': '0.7',
                    'position': 'fixed',
                    'top': '0px',
                    'width': '100%',
                    'z-index': '1000001'
                });
                $(this).css({ 'position': 'fixed',
                    'top': '50%',
                    'left': '50%',
                    'width': '130px',
                    'height': '130px',
                    'margin-top': '-65px',
                    'margin-left': '-65px',
                    'z-index': '1000002',
                    'display': 'block',
                    'border': '1px solid black',
                    'border-radius': '5px',
                    'background': " white url('" + spinnerObj.SpinnerUri + "') no-repeat center center"
                });
                $(this).show();
                //alert('test');
            })
            .ajaxStop(function () {
                $(this).hide();
                $('#bgSpinnerDiv').removeAttr("style").unbind('ajaxStart', UnBindAjaxStop($('#bgSpinnerDiv')));
                $(this).removeAttr("style").unbind('ajaxStart', UnBindAjaxStop(this));
            });
};

UnBindAjaxStop = function (me) {
    $(me).unbind('ajaxStop');
};

I call the method before an ajax call and pass it an object with the uri of the spinner gif, but the spinner and background do not display unless I have an alert. I have tried adding a setTimeout()function{/*do some code*/},1000) in various places, but that did not seems to help.

I saw a similar issue in this posting but the setTimeout does not seems to help. Any ideas?


回答1:


If your ajax request is being sent synchronously, the browser will be locked up immediately before it has time to render the spinner. When it's done, it will immediately hide the spinner, thus causing it to not display at all. The alert gave the browser enough time to render the spinner before sending the ajax request.

Remove async: false



来源:https://stackoverflow.com/questions/21712728/spinner-bound-to-ajax-call-will-not-display-unless-i-put-an-alert-in-the-javascr

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