2015-10-08 144 views
-1

我有一個實現幾個httprequest的函數。當所有這些請求藝術完成時,我需要刷新父窗口並關閉當前窗口。 但是現在當前窗口在完成請求之前關閉,並且請求沒有正確完成。 這裏是我的代碼:另一個異步函數結束時的Javascript調用函數

<script> 
     function save() 
     { 

      $.when(insert()).done(function() { 
       opener.location.reload(); 
       window.close(); 
      }); 

     } 

     function insert() 
     { 
      $('select').each(function() { 
       var idTraslado = $(this).attr("id"); 
       var accion = $(this).val(); 

       //the page realizes mysql updates. 
       xmlhttp = new XMLHttpRequest(); 
       xmlhttp.open("GET","trasladosEliminarMultipleGuardar.php?idTraslado="+idTraslado+"&accion="+accion+"&motivo="+motivo,true); 
       xmlhttp.send(); 
      }); 
     } 
    </script> 
+1

https://www.promisejs.org/你至少搜索? –

+1

__Why__如果你有jQuery,你在做'XMLHttpRequest'嗎?! – Mathletics

+0

我怎麼能用jQuery來做到這一點? –

回答

1

你必須使用的承諾,否則when已經在你的代碼沒有用:

function save() 
{ 
    $.when(insert()).done(function() { 
     opener.location.reload(); 
     window.close(); 
    }); 
} 

function insert() 
{ 
    var promises = []; 
    $('select').each(function() { 
     var deferred = $.Deferred(); 
     var idTraslado = $(this).attr("id"); 
     var accion = $(this).val(); 

     //the page realizes mysql updates. 
     xmlhttp = new XMLHttpRequest(); 
     xmlhttp.onload = function (response) { 
      deferred.resolve(response); 
     }; 
     xmlhttp.open("GET", "trasladosEliminarMultipleGuardar.php?idTraslado=" + idTraslado + "&accion=" + accion + "&motivo=" + motivo, true); 
     xmlhttp.send(); 
     promises.push(deferred.promise()); 
    }); 
    return promises; 
} 
+0

當第一個Ajax請求結束時,這不會被解決嗎?剩下的事會發生什麼? –

+0

對!沒有注意到,將用一種將返回一系列承諾的方法進行編輯 – taxicala

相關問題