2016-10-13 33 views
2

我打電話給AJAX使用$。當等到ajax完成並返回處理下一個ajax裏面。

這是$。當呼叫發生的情況:

function loadAllData(){ 
    $.when(getCreditorID()).done(function(a1){ 
     console.log("cx id is : " + parseFloat(a1[0])); //this is in the attached screen shot 
     var urlx = "functions/getCustomerData.php"; 
     $.post(
      urlx, 
      { 
       selectedValue: a1[0], 
      }, 
      function(data) { 
       $("#payduedate").val(data[0].duedate); 
       document.getElementById('portcode').value = data[0].portcode; 
       document.getElementById('currencycode').value = data[0].currencycode; 
       document.getElementById('convertion').value = data[0].conversion; 
      }, 
      "json" 
     ); 
    }); 
} 

上面的代碼調用下面AJAX方法功能:

function getCreditorID(){ 
    id = ""; 
    var creditorcodex = document.getElementById('creditorcode').value; 
    // console.log("getCreditorID input: " + creditorcodex); 
    var urlx = "functions/getCreditorID.php"; 
    return $.ajax({ 
     type: 'POST', 
     url: urlx, 
     data: { 
      creditorcode: creditorcodex, 
     }, 
     success: function(data) { 
      console.log("Result : "+data); //this is in the attached screen 
     } 
    }); 
} 

以上函數調用getCreditorID.php獲取數據: getCreditorID.php :

<?php 
    include '../config/dbConn.php'; 

    $creditorcode = $_POST["creditorcode"]; 
    // $creditorcode = $_GET["creditorcode"]; 
    $result=""; 

    $sql = "SELECT intCustomerID FROM lms.tblcustomers WHERE varCustomerName='".$creditorcode."';"; 

    mysql_select_db('$dbname'); 
    $retval = mysql_query($sql, $conn); 

    if(! $retval) 
    { 
     $result=-999; 
    } 
    while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) 
    { 
     $result=$row["intCustomerID"]; 
    } 
    echo $result; 
    mysql_close($conn); 
?> 

問題是: 如果從getCreditorID.php返回'44',那麼getCreditorID()函數中的console.log("Result : "+data);將在控制檯中輸出爲'Result:44',並且這工作正常。但是同樣的函數在loadAllData()函數中返回並使用爲下一個Ajax返回的值。這裏如果我們使用console.log("cx id is : " + parseFloat(a1[0]));打印返回值,則輸出爲'4',應該是'44'。這意味着它只會將第一個字符作爲輸出並忽略其餘部分。

運行控制檯的屏幕截圖: screen shot of running code

請找到出路。

+0

你爲什麼要這麼做'A1 [0]'爲什麼你能指望它來無回' 4'?數據是「44」,所以數據[0]將是'4' – apokryfos

+0

謝謝:明白了。 –

回答

0

在你的函數loadAllData(),用A1代替A1 [0]和更新代碼,因此

function loadAllData(){ 
    $.when(getCreditorID()).done(function(a1){ 
     console.log("cx id is : " + parseFloat(a1)); // did correction here 
     var urlx = "functions/getCustomerData.php"; 
     $.post(
      urlx, 
      { 
       selectedValue: a1[0], 
      }, 
      function(data) { 
       $("#payduedate").val(data[0].duedate); 
       document.getElementById('portcode').value = data[0].portcode; 
       document.getElementById('currencycode').value = data[0].currencycode; 
       document.getElementById('convertion').value = data[0].conversion; 
      }, 
      "json" 
     ); 
    }); 
} 
+0

您沒有更新$ .post方法中第二次使用a1。 – jcubic

+0

謝謝,這工作正常。再次感謝您糾正我。 –

+0

@jcubic:哈哈..是的,這就是爲什麼我提到「相應地更新你的代碼」。因爲我是一個懶惰的人..大聲笑。 –