2011-05-10 10 views
1

外部変数を成功関数にどのように送信できますか?jQuery - 外部変数をAjaxの成功関数に送信

は、私はあなたがローカル変数を作ることによってクロージャにアクセスすることができ、成功関数に

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

なぜ?なぜあなたはこれをしたいのですか?成功関数からsuccess変数にアクセスできます。また、success関数にも割り当てることができます。 –

+0

@maple_shaft:JavaScriptのクロージャーと呼ばれるローカル変数にアクセスしたいとします。 – Hogan

答えて

1

をthis.testを送りたいです。 シンプルなケース:

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(); 
    }; 
} 
関連する問題