jQuery.ajax()中的范围问题

alk*_*333 4 javascript ajax jquery closures

我通过将标签字符串保存到变量中来缓存标签字符串,但遇到了奇怪的范围问题.我知道这与闭包有关,但我似乎无法弄清楚究竟是什么问题.

info_lbl = {};

$("#chkCorporateGift").click(function(){
    var type = $(this).is(":checked") ? "Corporate" : "Personal";
    if(!info_lbl.hasOwnProperty(type)){
        $.ajax({
            url: svc_og + "Get" + type + "InformationLabel",
            success: function(data){
                info_lbl[type] = data;
            }
        });
    }
    $("#lblInformationType").text(info_lbl[type]);
});
Run Code Online (Sandbox Code Playgroud)

lblInformationType标签未在第一次调用GetCorporateInformationLabel或GetPersonalInformationLabel方法时设置.在第一次调用每个人之后,标签的值正在改变.有人可以解释为什么会出现这种情况吗?当我使用Firebug并设置断点时$("#lblInformationType").text(info_lbl[type]);,info_lbl[type]包含正确的值,并且前两个调用的一切正常.

use*_*716 5

AJAX调用是异步的.这意味着请求之后的任何代码都不会等待请求在运行之前返回.

换句话说,AJAX请求不会阻止后续代码行的执行.因此,当从AJAX请求收到响应时,已经执行了以下代码行.

依赖于AJAX请求的响应的任何代码应放在里面回调.

$("#chkCorporateGift").click(function(){
 //   var type = $(this).is(":checked") ? "Corporate" : "Personal";
    // It is more efficient to use this.checked instead of using .is(":checked")
    var type = this.checked ? "Corporate" : "Personal";
    if(!info_lbl.hasOwnProperty(type)){
        $.ajax({
            url: svc_og + "Get" + type + "InformationLabel",
            success: function(data){
                info_lbl[type] = data;
                  // code that relies on the response needs to be placed in
                  //   a callback (or in a function that is called here).
                $("#lblInformationType").text(info_lbl[type]);
            }
        });
    } else {
        $("#lblInformationType").text(info_lbl[type]);
    }
});
Run Code Online (Sandbox Code Playgroud)

我会想到,当你有一个断点时,事情正常工作的原因是执行中的暂停给了AJAX响应时间返回.


编辑:通过使用this.checked而不是原始代码提高代码的效率$(this).is(':checked').