2017-07-18 64 views
2

我有一些功能,使一些AJAX调用。
为了执行所有需要的方式,这些请求必须以async: false设置。

ajax调用一切正常。我的问题是,我需要一个div(一个简单的css加载器)在发送请求之前显示,然后隐藏,但它不显示。

这是我的函数:显示或隐藏div与异步错误阿贾克斯调用

$("#btn1").on('click', function(){ 
     // Apparently it does not executes this   
     $('.container-loader').show(); 
     //execute the function and handle the callback 
     doSomeStuff(function(c){ 
      if(!c.ok){ 
       showModalWarning(); 
       $('#text').append('<li>'+c.msg+'</li>'); 
      } 
      else{ 
       toastr.success('Everything is ok'); 
       doOtherStuff($("#select").val());    
      } 
     }); 

     var modal = document.getElementById('Modal1'); 
     modal.style.display = "none"; 
     return false; 
    }); 

doSomeStuff()功能,使请求:

function doSomeStuff(callback){  
      //... 
      for (var i = 0; i < ids.length; i++) { 
       var Id = ids[i][0]; 
       var ch = ids[i][1]; 
       var tp = 2;        
       var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + ch; 
       $.ajax({ 
        cache: "false", 
        async: false, //it needs to by with async false 
        dataType: 'json', 
        type: 'get', 
        url: url, 
        success: function(data) { 
         if (!data) 
          toastr.error('error'); 
        }, 
        error: function(jqXHR, textStatus, errorThrown) { 
         toastr.error("some problem"); 
        } 
       }); 
      } 
      callback({ok: true}); 
    } 

我如何能处理这个任何想法?我对于异步的东西非常陌生。

回答

0

通过删除异步并更改我的服务器中的方法来接收数组作为参数来解决此问题。

最终的脚本:

$("#btn1").on('click', function(){    
     //$('.container-loader').show(); 
     //execute the function and handle the callback 
     doSomeStuff(function(c){ 
      if(!c.ok){ 
       showModalWarning(); 
       $('#text').append('<li>'+c.msg+'</li>'); 
      } 
      else{ 
       toastr.success('Everything is ok'); 
       doOtherStuff($("#select").val());    
      } 
     }); 
    }); 

我doSomeStuff()函数,使请求:

function doSomeStuff(callback){  
      //... 
      var tp = 2;        
      var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + encodeURIComponent(JSON.stringify(jsonArray)); 
      $.ajax({ 
        cache: "false", 
        //async: false, //it needs to by with async false 
        dataType: 'json', 
        type: 'get', 
        url: url, 
        success: function(data) { 
         if (!data) 
         callback({ok: false}); 
        }, 
        error: function(jqXHR, textStatus, errorThrown) { 
         toastr.error("some problem"); 
        }, complete: function(){ //hide the loader after complete 
         $('.container-loader').hide(); 
         var modal = document.getElementById('Modal1'); 
         modal.style.display = "none"; 
        } 
      });     
    }