异步AJAX调用互相覆盖

时间:2013-02-25 21:48:24

标签: ajax jquery

我有一个仪表板页面,并且使用jQuery通过单个ajax调用来更新每个图形。

如果它使用async:false运行AJAX,那么一切正常,但是随着调用一个接一个地进行,它显然很慢。

当我运行async:true时,查询会执行,但它们都输出到同一个元素并相互覆盖。

如何确保成功和错误函数中的jQuery选择器仍然指向其原始设计并且不是都指向最后一个框?

我的代码:

//update sparklines on dashboard page
        $(".convobox7").each(function() {
            id = $(this).attr('id');
            $("#convobox-7-"+id).prepend("<img src='img/ajax_loader.gif'/>");
            $.ajaxQueue({
                url: '_ajax/getFunnelReport',
                type: "POST",
                dataType: "json",
                async: true,
                data: {funnel:$(this).attr('id'), dimension:'date'},
                timeout: 50000,
                success: function(json) { 
                    var data = json;
                    if (data.success=='true') {
                        $("#convobox-7-"+id).html(data.htmlconv+"<br/><small>Past week</small>");
                        gebo_peity.init();
                    }

                },
                error: function(x, t, m) {
                    $("#convobox-7-"+id).html("");
                }
            })
        });

注意我在这里使用的是ajaxQueue插件,但没有它就会发生同样的事情。

3 个答案:

答案 0 :(得分:2)

您需要本地化id

var id = $(this).attr('id');

可能还有其他事情需要解决,但确定无疑。

修改

试试这个:

$(".convobox7").each(function() {
    var id = $(this).attr('id');
    var $el = $("#convobox-7-"+id).prepend("<img src='img/ajax_loader.gif'/>");
    $.ajaxQueue({
        url: '_ajax/getFunnelReport',
        type: "POST",
        dataType: "json",
        data: {funnel:id, dimension:'date'},
        timeout: 50000,
        success: function(data) {
            if (data.success == 'true') {
                $el.html(data.htmlconv+"<br/><small>Past week</small>");
                gebo_peity.init();
            }
        },
        error: function(x, t, m) {
            $el.html("");
        }
    });
});

答案 1 :(得分:1)

这与函数闭包有关,因为您在成功/错误函数之外声明了变量。更好的方法是在错误/成功函数中使用$(this)引用,而不是在处理程序之外分配它。

编辑:在ajaxQueue的错误/成功处理程序的上下文中,我不完全确定$(this)引用的内容,您可能需要导航到父元素。我没有看到任何明确的文件。这是我最大的烦恼之一,带有javascript文档,$(这个)有时不是你认为的那样而且没有记录:/

答案 2 :(得分:0)

愚蠢的问题,但既然你已经将元素id发送给服务,是否有理由无法将其发回?然后你可以简单地将它用作选择器,确保你拥有所需的物品。

相关问题