简体   繁体   English

jQuery .done() .fail()

[英]jQuery .done() .fail()

What we want here is to manipulate the createSite function expected return which is {ac:failed} so when it failed .fail(failOption) will be execute else sendMail / .done(sendMail) function will execute and still holding the data from createSite function which is the {bar1:"foo1",bar2:"foo2",bar3:"foo3"}我们在这里想要的是操作createSite函数的预期返回值{ac:failed}所以当它失败时.fail(failOption)将被执行 else sendMail / .done(sendMail)函数将执行并仍然保持来自createSite函数的数据这是{bar1:"foo1",bar2:"foo2",bar3:"foo3"}

var cSite = createSite(); //expected return if failed is {ac:"failed"} else success expected return will be {bar1:"foo1",bar2:"foo2",bar3:"foo3"}


var cSite = createSite();
cSite.done(sendMail).fail(failOption).always(alwaysOption);

function createSite() {
    return $.ajax({
        url: 'something.php',
        method: 'POST',
        data: "template_id=" + template_id + "&original_url=" + original_url + "&email=" + email + "&first_name=" + first_name + "&last_name=" + last_name
    }); //ajax
} //createSite

jQuery's fail part of the ajax promise is triggered on http statuses other than the 200 range I imagine, like 400: bad request or 500: internal server error . jQuery 的ajax承诺的fail部分是在我想象的 200 范围以外的 http 状态上触发的,例如400: bad request500: internal server error

If you cannot pass a fail status from something.php , there are two options.如果您无法从something.php传递失败状态,则有两种选择。 For jQuery 1 and 2:对于 jQuery 1 和 2:

function createSite() {
    var promise = $.Deferred();

    $.ajax({
        url: 'something.php',
        method: 'POST',
        data: "template_id=" + template_id + "&original_url=" + original_url + "&email=" + email + "&first_name=" + first_name + "&last_name=" + last_name
    }).then(function(data) {
        if(data.ac === 'failed') {
            promise.reject(failed)
        } else {
            promise.resolve(data);
        }
    })

    return promise;
}

In newer versions of jQuery (3+), you can also throw an error to trigger a fail :在较新版本的 jQuery (3+) 中,您还可以抛出错误以触发fail

function createSite() {
    return $.ajax({
        url: 'something.php',
        method: 'POST',
        data: "template_id=" + template_id + "&original_url=" + original_url + "&email=" + email + "&first_name=" + first_name + "&last_name=" + last_name
    }).then(function(data) {
        if(data.ac === 'failed') {
            throw data
        } else {
            return data
        }
    });
}

Please note that this is completely untested.请注意,这完全未经测试。 The documentation for deferred is here . deferred的文档在这里

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

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