jquery deferred 和 return false 基于服务器响应

jquery deferred and return false based on server response

我有以下 jquery 延迟逻辑。

var $qCallA = callA();
var $qCallB = callB();

$.when($qCallA,$qCallB).then(function () {
        $("#spinnerDiv").removeClass('spinner show');
});

function callA() {
    return $.getJSON("/callA", function (data) {
        if (data.status === "success") {
            buildTable1(data);
        }
    });
}

function callB() {
    return $.getJSON("/callB", function (data) {
        if (data.status === "success") {
            buildTable2(data);
        }
    });
}

我想根据后端 json 的响应为 $.getJSON 调用设置 return false。 例如,如果 data.status == "failure" 那么我想 return "false" for getJSON。 如何实现?

谢谢

听起来您想使用适当的 then 回调,您可以在其中 return 承诺的新结果值:

$.when(callA(), callB()).then(function(a, b) {
    $("#spinnerDiv").removeClass('spinner show');
    if (a && b) …
});

function callA() {
    return $.getJSON("/callA").then(function(data) {
        if (data.status === "success") {
            buildTable1(data);
        }
        return data.status != "failure";
    });
}

function callB() {
    return $.getJSON("/callB").then(function(data) {
        if (data.status === "success") {
            buildTable2(data);
        }
        return data.status != "failure";
    });
}

您应该为 $.getJSON 提供成功回调 then 并为 $.when 提供 return 自定义 Deffered 来处理。

这样您就可以根据 JSON.

中的数据手动解决或拒绝
var $qCallA = callA();
var $qCallB = callB();

$.when($qCallA,$qCallB).then(function (s1, s2) {
    $("#spinnerDiv").removeClass('spinner show');
}).fail(function() {
    //handle failure
});

function callA() {
    return $.getJSON("/callA").then(function (data) {
        if (data.status === 'failure') {
        return $.Deferred().reject("A: no success");
      }
      return $.Deferred().resolve(data);      
    });
}

function callB() {
    return $.getJSON("/callB").then(function (data) {
        if (data.status === 'success') {
        return $.Deferred().resolve(data);
      }
      return $.Deferred().reject("B: no success");
    });
}

Similar JSFiddle