2016-09-22 89 views
0

我想獲得ajax的返回值。請幫助我的代碼不返回值爲false或true。如何通過ajax傳遞值來實現功能

我在這個腳本的validate(兩個功能),其調用validateDate()的AJAX是本

<script type="text/javascript"> 
    $(document).ready(function(){ 

    function validateDate(date) { 

    return $.ajax({ 
      type: "POST", 
      url: "<?php echo base_url(); ?>activate/checkdate", 
      data: "Date_of_Birth="+date, 
      success: function(msg){ 
       if(msg=="false"){ 
         return false; 
       } 
       else{ 
         return false; 
       } 
      } 
     }); 
    } 

function validatesa() { 
    var date = $("#Datepicker").val(); 
    if (validateDate(date)) { 
     return true; 
     } else { 
     sweetAlert(date , "is not a valid date YYYY-MM-DD", "error"); 
    return false; 
     } 
    } 
    }else { 
     sweetAlert(date , "is not a valid date YYYY-MM-DD", "error"); 
     return false; 
     } 
    } 
    $("form").bind("submit", validatesa); 

}); 

</script> 

回答

0

AJAX是異步處理,以便返回不允許的。在你的情況下,你必須在你的ajax請求選項中使用async : false。廣告必須使用返回變量。所以你的功能代碼應該是。

function validateDate(date) { 
    var response=""; 
    $.ajax({ 
     type: "POST", 
     url: "<?php echo base_url(); ?>activate/checkdate", 
     async: false, 
     data: { 
      Date_of_Birth: date 
     }, 
     success: function(msg) { 
      if (msg == "false") { 
       response = false; 
      } else { 
       response = true; 
      } 
     } 
    }); 
    return response; 
} 
0

感謝您的解釋。它幫助了很多。改變一些腳本評論感謝很多

function validateDate(date) { 
    var response=""; // i assign as empty first since ajax success dont have value yet 
    $.ajax({ 
    type: "POST", 
    url: "<?php echo base_url(); ?>activate/checkdate", 
    async: false, 
    data: { 
     Date_of_Birth: date 
    }, 
    success: function(msg) { 
     if (msg == "false") { 
      response = false; // assign false to response variable since false is the output. 
     } else { 
      response = true; 
     } 
     } 
    }); 
    return response; 
}