2011-05-10 92 views
1

如何将外部变量发送到成功函数中?jQuery - 将外部变量参数发送到ajax成功函数

我想this.test送入成功的功能

function Ajax(){ 
    this.url = null; 
    this.data = null; 
    this.success = null; 

    this.timeout = JSON_TIMEOUT; 
    this.cache = false; 
    this.dataType = 'json'; 
    this.type = 'post'; 

    this.send = function(){ 
     var jqxhr = $.ajax({ 
       url : this.url, 
       data : this.data, 
       timeout : this.timeout, 
       cache : this.cache, 
       dataType : this.dataType, 
       type : this.type 
       } 
      ) 
      .success(this.success); 
    }; 
} 

function Login(){ 
    this.client = null; 
    this.user = null; 
    this.pass = null; 

    this.test = 'test'; 

    this.send = function(client, user, pass){ 
     var Obj = new Ajax(); 
     Obj.url = 'json.action.php?action=login'; 
     Obj.data = { 
      client : this.client, 
      user : this.user, 
      pass : this.pass 
      }; 
     Obj.success = function(response){ 
      alert(this.test); 
      alert(response); 
      //window.location.href = window.location.href; 
      }; 
     Obj.send(); 
    }; 
} 
+0

为什么?我看不出有什么理由为什么你想这样做?您可以从成功功能访问成功变量,也可以指定它。 – 2011-05-10 11:12:16

+0

@maple_shaft:他想访问一个局部变量,在JavaScript中称为闭包。 – Hogan 2011-05-10 11:16:03

回答

1

您可以通过一个局部变量访问关闭。 简单的情形:

function Login(){ 
    this.client = null; 
    this.user = null; 
    this.pass = null; 

    this.test = 'test'; 

    var closureVar = 'test'; 

    this.send = function(client, user, pass){ 
     var Obj = new Ajax(); 
     Obj.url = 'json.action.php?action=login'; 
     Obj.data = { 
      client : this.client, 
      user : this.user, 
      pass : this.pass 
      }; 
     Obj.success = function(response){ 
      alert(closureVar); 
      alert(response); 
      //window.location.href = window.location.href; 
      }; 
     Obj.send(); 
    }; 
} 

复杂的情况:

function Login(){ 
    this.client = null; 
    this.user = null; 
    this.pass = null; 

    this.test = 'test'; 

    var closureVar = this; 

    this.send = function(client, user, pass){ 
     var Obj = new Ajax(); 
     Obj.url = 'json.action.php?action=login'; 
     Obj.data = { 
      client : this.client, 
      user : this.user, 
      pass : this.pass 
      }; 
     Obj.success = function(response){ 
      alert(closureVar.text); 
      alert(response); 
      //window.location.href = window.location.href; 
      }; 
     Obj.send(); 
    }; 
} 
相关问题