2014-01-17 70 views
0

循環我有一個for循環,調用一個AJAX方法阿賈克斯在沒有jQuery的

function viderTableauConteneur() 
{ 
    var caf = document.getElementById('CAF').value; 
    var tabConteneurAjouter = caf.split("#"); 
    for (var i = 0; i < tabConteneurAjouter.length; i++) { 
     if(!verifierConteneurAppartienClient(tabConteneurAjouter[i])); 
      removeConteneur(tabConteneurAjouter[i]); 
    }; 

} 

function verifierConteneurAppartienClient(serialNumber) 
{ 
    var e = document.getElementById("id_client"); 
    var idClient = e.options[e.selectedIndex].value; 
    var xhr = getXhr(); 
    var res = 12; 
    xhr.onreadystatechange = function() 
    { 

     if(xhr.readyState == 4 && xhr.status == 200) 
     { 
      if(xhr.responseText == "0") 
       return false; 
      else if(xhr.responseText == "1") 
       return true; 
     } 

    } 
    xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=verifierConteneurAppartienClient&refConteneur="+serialNumber+"&id_client="+idClient,true); 
    xhr.send(); 


} 

好吧,如果我提醒xhr.responseText我得到了「1」,但是當我在viderTableauConteneur方法,我總是提醒結果得到了 「Undifined

任何幫助,請

+0

進一步看你的代碼。 'verifierConteneurAppartienClient'本身返回的結果是什麼?答案是「none」 - 只有在嵌套回調中,該函數中沒有'return'語句。 – Alnitak

+0

謝謝你我讀過這個,但我沒有注意其他答案 – Rad

回答

0

你可以修改你的代碼是這樣的:

function viderTableauConteneur() 
{ 
    var caf = document.getElementById('CAF').value; 
    var tabConteneurAjouter = caf.split("#"); 
    for (var i = 0; i < tabConteneurAjouter.length; i++) { 
     verifierConteneurAppartienClient(tabConteneurAjouter[i], 
      function() 
      { 
       alert('true'); 
      }, 
      function() 
      { 
       alert('false'); 
       removeConteneur(tabConteneurAjouter[i]) 
      } 
     ); 
    } 
} 

/* callbcakIfTrue and callbackIfFalse have to be 2 functions 
    that will be called respectiveley if the return of the 
    ajax call is true or false. 
*/ 
function verifierConteneurAppartienClient(serialNumber, callbackIfTrue, callbackIfFalse) 
{ 
    var e = document.getElementById("id_client"); 
    var idClient = e.options[e.selectedIndex].value; 
    var xhr = getXhr(); 
    var res = 12; 
    xhr.onreadystatechange = function() 
    { 

     if(xhr.readyState == 4 && xhr.status == 200) 
     { 

      if(xhr.responseText == "1") 
       callbackIfTrue(); 
      else 
       callbackIfFalse(); 

     } 

    } 
    xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=verifierConteneurAppartienClient&refConteneur="+serialNumber+"&id_client="+idClient,true); 
    xhr.send(); 


}