简体   繁体   English

内部有两个AJAX函数,一个或另一个工作,但互斥

[英]Two AJAX functions inside, it works one or the other but mutually exclusive

This is the piece of code which I refer to: The first ajax call is: $.ajax(urlHoveringBtn) , the second is $.ajax(url) Just one or the other element. 这是我引用的代码:第一个ajax调用是: $.ajax(urlHoveringBtn) ,第二个是$.ajax(url)只是一个或另一个元素。 What's wrong? 怎么了?

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

try this 尝试这个

$(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 will make sure both the ajax calls were resolved and then executes the call back. $.when将确保两个ajax调用均已解决,然后执行回叫。

a1 and a2 are the response of the ajax calls ajax1 and ajax2 a1a2是ajax调用ajax1ajax2

for more info check the $.when docs http://api.jquery.com/jquery.when/ 有关更多信息,请检查$.when文档http://api.jquery.com/jquery.when/

urlHoveringBtn and url should be object here, not string. urlHoveringBtnurl应该是此处的对象,而不是字符串。 like: 喜欢:

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

Do same for url , this should work. url执行相同操作,这应该可以工作。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM