内部有两个AJAX函数,它可以相互作用,也可以相互排斥

时间:2014-01-07 17:43:24

标签: javascript jquery ajax

这是我所指的代码段: 第一个ajax调用是:$.ajax(urlHoveringBtn),第二个是$.ajax(url) 只是一个或另一个元素。怎么了?

$(document).on("click", "a.selection", function (e) {
    var $this = $(this);
    var isLive = $this.data("live");
    var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
    var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;

    $.ajax(urlHoveringBtn).done(function (dataBtn) {
        if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
            $("body").append(dataBtn);
        }
    });

    $.ajax(url).done(function (data) {
        if ($(".betslip-access").length == 0 && data.length > 0) {
            $(".navbar").append(data);
        }
        if (data.length > 0) {
            $this.addClass("in-betslip");
        }
    });
    e.preventDefault();
});

2 个答案:

答案 0 :(得分:1)

试试这个

$(document).on("click", "a.selection", function (e) {
        var $this = $(this);
        var isLive = $this.data("live");
        var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
        var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;

    var ajax1 = $.ajax(urlHoveringBtn);

    var ajax2 = $.ajax(url);

    $.when( ajax1, ajax2 ).done(function( a1, a2 ) {
        if ($(".betslip-access-button").length == 0 && a1.length > 0) {
                $("body").append(a1);
        }

      if ($(".betslip-access").length == 0 && a2.length > 0) {
            $(".navbar").append(a2);
        }
        if (data.length > 0) {
            $this.addClass("in-betslip");
        }
    });

    e.preventDefault();
});

$.when将确保两个ajax调用都已解决,然后执行回调。

a1a2是ajax调用ajax1ajax2

的回复

了解详情,请查看$.when文档http://api.jquery.com/jquery.when/

答案 1 :(得分:-1)

urlHoveringBtnurl应该是对象,而不是字符串。像:

var urlHoveringBtn = {
    url: "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection"),
    data : {
       odds : $this.data("odds"),
       live : isLive
    }
}

url执行相同操作,这应该可行。祝你好运!