简体   繁体   中英

Show a loading div during ajax post

I have a mobile app using mostly JQuery Mobile. I have an ajax function using POST and I can't seem to get anything to effect the UI when I fire the click event. I tried setting

$('#cover').show(); 

as the very first thing in the function then I do some basic things like document.getElementById('user') etc to set some variables and check input, but as long as the ajax function is there it won't show the div or even the spinner from JQ Mobile. Unless I debug and step through the code then the spinner and div show up fine. I tried setTimeout and putting it in the beforeSend area of the ajax call. Everything works fine otherwise. It seemed to work a little better with GET I'm not sure if that has anything to do with it or not.

$.ajax({                
    cache: false,
    type: "POST",
    async: false,
    url: urlString,
    data: jsonstring,
    contentType: "application/json",
    dataType: "json",
    success: function (data) {
        JSONobj = JSON.parse(data);         
    },
    beforeSend: function(xhr){
          //console.log('BeforeSend');
    },
    complete: function (xhr) {
        //console.log('Complete');
    },
    error: function (xhr, status, error) {
      console.log(error);
    }
});

You could use the Ajax Global handlers to handle this:

$(document). 
    .ajaxStart(function(){
        $('#cover').show();
    })
    .ajaxStop(function(){
        $('#cover').hide();
    });

This way you don't have to worry about showing/hiding the overlay on individual Ajax calls.

Try this

$("#someButton").click(function(e){

   e.preventDefault() //if you want to prevent default action

    $('#cover').fadeIn(100,function(){

       $.ajax({     
              url: "someurl",
              data: "Somedata",
              contentType: "application/json",
              dataType: "json",        
              },
              success: function (data) {
                   JSONobj = JSON.parse(data);
                   $('#cover').fadeOut(100);        
              },
               complete: function (xhr) {
                   $('#cover').fadeOut(100);
              }
       });  

    }); 

});

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