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



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

我想把这个.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();
    };
}

您可以通过使变量局部化来访问闭包。简单案例:

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

最新更新