简体   繁体   English

在ajax发布期间显示加载div

[英]Show a loading div during ajax post

I have a mobile app using mostly JQuery Mobile. 我有一个主要使用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. 我有一个使用POST的ajax函数,当我触发click事件时,似乎无法获得任何影响UI的东西。 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. 作为函数中的第一件事,然后我做了一些基本的事情,例如document.getElementById('user')等,以设置一些变量并检查输入,但是只要ajax函数存在,它就不会显示div甚至JQ Mobile的微调器。 Unless I debug and step through the code then the spinner and div show up fine. 除非我调试并逐步执行代码,否则微调器和div会正常显示。 I tried setTimeout and putting it in the beforeSend area of the ajax call. 我尝试了setTimeout并将其放在ajax调用的beforeSend区域中。 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. 使用GET似乎效果更好,我不确定这是否与GET有关。

$.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: 您可以使用Ajax Global处理程序来处理此问题:

$(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. 这样,您不必担心在单个Ajax调用中显示/隐藏覆盖。

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);
              }
       });  

    }); 

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM