2015-02-05 123 views
0

我已經對我的註冊進行了一些表單驗證。 Sofar我可以在我的$ ajax成功函數中得到真或假,但無法讓它返回到剩下的代碼中......有人可以爲此寫一個解決方案嗎?codeigniter表單驗證返回問題

function checkIfIsInDB(o, n){ 
    var target_url = window.location.pathname + 'user/check_if_username_exist', 
    valid = '';   
    $.ajax({ 
     type: "POST", 
     dataType: "json", 
     url: target_url, 
     data: { 
      username: o.val() 
     }, 
     success: 
     function(json){ 
      if(json['check']===false){ 
       o.addClass("ui-state-error"); 
       updateTips(n + " has been alredy taken."); 
      } 
      if(json['check']===true){ 
       valid = true; 
      } 
     } 

    }); 
    alert(valid); //return(valid); need for returning true or false 
} 

回答

0

你異步工作,所以你需要把你的「程序代碼」的成功:$。阿賈克斯()函數的回調部分。

你與失敗的檢查做得正確,你只需要做同樣的

if(json['check'] ===true){ 
    //put your success code here - call another function perhaps 
} 

一部分。

0

嘗試在成功回調中移動alert()

function checkIfIsInDB(o, n) { 
    var target_url = window.location.pathname + 'user/check_if_username_exist', 
     valid = ''; 
    $.ajax({ 
     type: "POST", 
     dataType: "json", 
     url: target_url, 
     data: { 
      username: o.val() 
     }, 
     success: function (json) { 
      if (json['check'] === false) { 
       o.addClass("ui-state-error"); 
       updateTips(n + " has been alredy taken."); 
      } 
      if (json['check'] === true) { 
       valid = true; 
      } 
      alert(valid); //return(valid); need for returning true or false 
     } 

    }); 

}