jQuery - 将外部var参数发送到ajax成功函数

时间:2011-05-10 11:09:06

标签: jquery

如何将外部变量发送到成功函数?

我想将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();
    };
}

1 个答案:

答案 0 :(得分: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();
    };
}