2017-07-09 61 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>