jQuery .done()。fail()

时间:2017-01-25 08:18:04

标签: javascript jquery ajax

我们想要的是操纵createSite函数预期返回{ac:failed},因此当失败时.fail(failOption)将执行其他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

1 个答案:

答案 0 :(得分:0)

jQuery fail承诺的ajax部分是在除我想象的200范围之外的http状态触发的,例如400: bad request500: internal server error

如果您无法从something.php传递失败状态,则有两种选择。对于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;
}

在较新版本的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
        }
    });
}

请注意,这是完全未经测试的。 deferred的文档为here