简体   繁体   English

jQuery ajax成功回调的范围?

[英]Scope of the jquery ajax success callback?

if I have 如果我有

function AjaxRequest(){
    var testvar = 0;
    for(i=0;i<d.length;i++){
        $.ajax({
            success: function(a){
                testvar++;
            }

        });
    }
}

Will testvar increase on success? testvar成功会增加吗?

Yes; 是; the variable is captured by the function's closure. 该变量由函数的闭包捕获。
Closures keep variables alive so that nested functions can still use them later. 闭包使变量保持活动状态,以便嵌套函数以后仍可以使用它们。

Note that the success callbacks only run some time after the rest of your code finishes (AJAX is asynchronous). 请注意, success回调仅在其余代码完成之后(AJAX是异步的)运行一段时间。

Yes, it will. 是的,它会的。 It's similar to this: 与此类似:

function() {
   var self = this;
    this.a = function(){
        self.something;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM