简体   繁体   中英

Unable to display spinner before projecting dialog box

I have a dialog box to be displayed, before creating the dialog box to be displayed I would like to display a spinner on screen saying loading. My code actually looks like below.

    var $loading = $('#loadingDiv');
    $loading.show();
    console.log("spinner displayed in build");
    loadBuildsList(); // Just to give 6 seconds delay
    $("#buildSelectionDialog").dialog("open"); // display dialog
    console.log("spinner hidden in build");
    //$loading.hide()

Now, The problem I am facing is the loading div was supposed to appear on the screen before dialog box. But actually both dialog box and spinner appears at the same time. While debugging in browser if I introduce a break point at the line loadBuildsList(); the spinner displays before dialog box and if I let the code run without any break points both of them appears at the same time. The above problem print spinner displayed in build into console,halts for 6 seconds and then prints spinner hidden in build . But while displaying both spinner and dialog box appears at the same time. I am using ajax request to intrduce 6 seconds delay. Can anybody please tell How can I make the code work as I need?

My loadingDiv looks like below.

<div id="loadingDiv" style="top:30%; left:30%; position:fixed; width:200px; height:200px; z-index:9999999999; display:None">
<img width=150px height=150px src="ajax_loader.gif"/>
<p>This may take few seconds</p></div>

function loadBuildsList looks like below

function loadBuildsList() {
$.ajax({
async:false,
url:"ajax_test.php"
});
}

Rather than trying to make the AJAX request synchronous to make things happen in order jQuery.ajax returns a promise so we can return that from loadBuildsLists to allow us to handle things in the correct order whilst keeping the AJAX request asynchronous.

    function loadBuildsList() {
      return $.ajax({
        url:"ajax_test.php"
      });
    }

Then if we modify your code slightly we can add a callback function from outside of loadBuildsList which should allow things to happen in the correct order:

    var $loading = $('#loadingDiv');
    $loading.show();
    console.log("spinner displayed in build");
    loadBuildsList()
        .done(function(data){ // As a promise is returned we can add a callback via the "done" method. 
            $("#buildSelectionDialog").dialog("open"); 
            console.log("spinner hidden in build");
            //$loading.hide()
         }); // Just to give 6 seconds delay

The .fail() , and .always() methods of the jQuery promise may also be of interest to you the full documentation for Deferred is available here http://api.jquery.com/jQuery.Deferred/

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