jQuery.ajax() 内部的范围问题

发布于 2024-09-27 19:39:15 字数 776 浏览 3 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

咿呀咿呀哟 2024-10-04 19:39:15

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') 提高了代码效率。

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.

$("#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]);
    }
});

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').

本宫微胖 2024-10-04 19:39:15

将此行:

        $("#lblInformationType").text(info_lbl[type]);

移至“成功”回调中。

Move this line:

        $("#lblInformationType").text(info_lbl[type]);

into the "success" callback.

虚拟世界 2024-10-04 19:39:15

如上所述,有两种解决方案:

1)使 $.ajax 异步

$.ajax({
    url: svc_og + "Get" + type + "InformationLabel",
    async: false,
    success: function(data){
        info_lbl[type] = data;
    }
});

2)保持异步但执行两次:

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(data);
        }
    });
}
$("#lblInformationType").text(info_lbl[type]);

As said above, there is 2 solutions :

1) Making $.ajax asynchronous

$.ajax({
    url: svc_og + "Get" + type + "InformationLabel",
    async: false,
    success: function(data){
        info_lbl[type] = data;
    }
});

2) Keep it asynchronous but doing twice :

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(data);
        }
    });
}
$("#lblInformationType").text(info_lbl[type]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文