代码之家  ›  专栏  ›  技术社区  ›  geoff swartz

jquery与map/each延迟

  •  1
  • geoff swartz  · 技术社区  · 14 年前

    我以前没有使用过延期,但我在这里和那里读了一些关于延期的文章,据我所知,这听起来像是解决我目前面临的问题的办法。我有一个页面,必须在上面加载4个广告。以前,由于服务器查询每个广告的数据库所需的时间,页面速度减慢。所以我将横幅广告调用转移到了web服务。这很好,但是如果我没有广告,我需要隐藏容器div,这意味着我需要知道所有ajax调用何时完成,然后检查是否加载了任何广告。

    我有下面的代码,它成功地调用了web服务并加载了广告,但then()函数似乎没有正常工作。它似乎是在ajax调用完成之前执行的。我从该页面获取代码 JQuery deferred with .each() 我能看到的唯一区别是,在他们的例子中,它显示了在deferred中返回函数调用。但我尝试过用return{}包围函数inneds,但它只是抛出了一个错误(意外的令牌“=”)。有人能告诉我我做错了什么吗?谢谢

      var deferreds = $(".ad").map(function () {
    
        var t = $(this);
    
        $.ajax({
            type: "POST",
            url: "/Services/Services.asmx/GetBanner",
            data: "{'bannerId':" + t.attr("bannerid") + ",'siteId':" + sid + ",'dt':'" + new Date().toString() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        })
        .success(function(data) {
            if (data.d.Banner != null && data.d.Banner != undefined) {
                t.html("<div class=\"featuredAd\">" + data.d.Banner + "</div>");
            }
        });
    });
    
    $.when.apply(null, deferreds.get()).then(function () {
        if($(".featuredAd").length > 0)
            $("#dvFeaturedBottom").show();
    });
    
    1 回复  |  直到 14 年前
        1
  •  0
  •   Kevin B    14 年前

    你没有归还承诺对象。

      var deferreds = $(".ad").map(function () {
    
        var t = $(this);
    
        return $.ajax({
            type: "POST",
            url: "/Services/Services.asmx/GetBanner",
            data: "{'bannerId':" + t.attr("bannerid") + ",'siteId':" + sid + ",'dt':'" + new Date().toString() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        })
        .done(function(data) {
            if (data.d.Banner != null && data.d.Banner != undefined) {
                t.html("<div class=\"featuredAd\">" + data.d.Banner + "</div>");
            }
        });
    });
    
    $.when.apply($, deferreds.get()).then(function () {
        if($(".featuredAd").length > 0)
            $("#dvFeaturedBottom").show();
    });