2017-07-09 63 views
1

我想阻止一個函數執行之前從ajax獲取值,我試圖使用async:false它的作品,但不推薦使用。所以,我正在使用像我在互聯網上發現的回調。這也是有效的,但瀏覽器仍然告訴我,回調是不是函數。這裏是我的代碼使用Ajax回調

function User() { 
 
    this.nama; 
 
    this.nis; 
 
    this.pass; 
 
    this.role; 
 
    this.url = "http://localhost/elearning-web/"; 
 
    
 
    this.Login = function(call) { 
 
     $.ajax({ 
 
      type:"POST",url:this.url+"dologin.php",data:"nis="+this.nis+"&pass="+this.pass, 
 
      success:function(e){ 
 
       call(e); 
 
      } 
 
     }); 
 
    } 
 
}

當我檢查它的表現我想顯示什麼的console.log,但瀏覽器告訴我,如果調用(回調)不是一個函數。在此先感謝

+0

你甚至在哪裏定義了函數「call」 –

+2

顯示如何調用'User.Login'as per [mcve] – charlietfl

+0

你將函數作爲「call」傳遞給了什麼? –

回答

2

你想要的是已經實現的使用無極API做的,是的,jQuery的支持太什麼。

你只需要改變,如下Login功能:

function User() { 
    // .. other code truncated for brevity 

    this.Login = function() { 
    return $.ajax({ 
     type: 'POST', 
     url: 'your_url' 
     // Note that `success` function has been removed from here 
    }); 
    } 
} 

現在這解決了很多問題。首先,User.Login的調用者不需要傳遞迴調函數。登錄功能可以只使用這樣的:

var user = new User(); 

user.Login() 
    .then(function(e) { 
    // `e` is accessible here 
    }); 

其次,可以是.then()相互鏈接的數量不受限制,提供更好的代碼的可讀性。

第三,由於.then接受函數作爲它的參數(免費驗證它),所以不需要驗證回調是一個函數。

四,success回調被jQuery棄用。 .then()使用新的語法。

2

call說法,要傳遞給方法Login必須是一個函數,例如:

var call = somethingFunction(){ return 'called!';} 
var user = new User(); 
user.Login(call) 
0

你必須declarate通話功能它通到User.Login(電話);

function call1(e) { 
 
    console.log('Hi, from call ', e); 
 
} 
 

 
function User1() { 
 

 
    this.Login = function(call) { 
 
     // simulating $.ajax http request ;] 
 
     setTimeout(function() { 
 
      call(';)'); 
 
     }, 2000); 
 
    } 
 
} 
 

 
var user1 = new User1(); 
 
user1.Login(call); 
 

 
// in your case 
 
function call(e) { 
 
    console.log('Hi, from call ', e); 
 
} 
 

 
function User() { 
 
    this.nama; 
 
    this.nis; 
 
    this.pass; 
 
    this.role; 
 
    this.url = "http://localhost/elearning-web/"; 
 
    
 
    this.Login = function(call) { 
 
     $.ajax({ 
 
      type:"POST", 
 
      url:this.url+"dologin.php", 
 
      data:"nis="+this.nis+"&pass="+this.pass, 
 
      success:function(e){ 
 
       call(e); 
 
      } 
 
     }); 
 
    } 
 
} 
 

 
var user = new User(); 
 
user.Login(call);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>