jQuery.ajax() 内部的范围问题
我通过将标签字符串保存到变量中来缓存标签字符串,但遇到了奇怪的范围问题。我知道这与关闭有关,但我似乎无法弄清楚问题到底是什么。
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]);
});
第一次调用 GetCorporateInformationLabel 或 GetPersonalInformationLabel 方法时,不会设置 lblInformationType 标签。第一次调用每个标签后,标签的值就会发生变化。有人可以解释一下为什么会出现这种行为吗?当我使用 Firebug 并在 $("#lblInformationType").text(info_lbl[type]);
上设置断点时,info_lbl[type]
包含正确的值并且前两次通话一切正常。
I'm caching label strings by saving them into a variable, but running into weird scoping issues. I know this has to do with closures, but I can't seem to figure out what the issue is exactly.
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 label isn't set the very first time GetCorporateInformationLabel or GetPersonalInformationLabel methods are called. After the first time each one is called, the label's value is being changed. Could somebody please explain why this behavior occurs? When I use Firebug and set a break point on $("#lblInformationType").text(info_lbl[type]);
, info_lbl[type]
contains the right value and everything works fine on the first two calls as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
AJAX 调用是异步的。这意味着请求后面的任何代码在运行之前都不会等待请求返回。
换句话说,AJAX 请求不会阻止后续代码行的执行。因此,当收到 AJAX 请求的响应时,以下代码行已经执行。
任何依赖 AJAX 请求响应的代码都应放置在回调内。
我认为,当你有一个断点时,一切正常工作的原因是执行的暂停给了 AJAX 响应返回的时间。
编辑:通过使用
this.checked
而不是原始的$(this).is(':checked')
提高了代码效率。AJAX calls are asynchronous. This means that any code following the request does not wait for the request to return before it runs.
In other words, the AJAX request does not block execution of subsequent lines of code. So by the time the response is received from the AJAX request, the following lines of code have already executed.
Any code that relies on the response of the AJAX request should be placed inside the callback.
I would image that the reason things work properly when you have a breakpoint is that the pause in execution gives the AJAX response time to return.
EDIT: Improved efficiency of the code by using
this.checked
instead of the original$(this).is(':checked')
.将此行:
移至“成功”回调中。
Move this line:
into the "success" callback.
如上所述,有两种解决方案:
1)使 $.ajax 异步
2)保持异步但执行两次:
As said above, there is 2 solutions :
1) Making $.ajax asynchronous
2) Keep it asynchronous but doing twice :