2017-07-18 65 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"; 
        } 
      });     
    }