我通过将标签字符串保存到变量中来缓存标签字符串,但遇到了奇怪的范围问题。我知道这与关闭有关,但我似乎无法弄清楚问题到底是什么。
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]);
});
lblInformationType 标签不是在第一次调用 GetCorporateInformationLabel 或 GetPersonalInformationLabel 方法时设置的。在第一次调用每一个之后,标签的值被改变。有人可以解释为什么会发生这种行为吗?当我使用 Firebug 并在 $("#lblInformationType").text(info_lbl[type]);
上设置断点时,info_lbl[type]
包含正确的值并且前两个调用也一切正常。
最佳答案
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]);
}
});
我想,当你有一个断点时,事情正常工作的原因是执行中的暂停给了 AJAX 响应时间来返回。
编辑: 通过使用 this.checked
提高了代码效率而不是原来的 $(this).is(':checked')
.
关于javascript - jQuery.ajax() 中的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3918221/