捕获错误时阻止JQuery继续

时间:2013-09-06 09:17:45

标签: javascript ajax jquery

文件准备好后我已经设置

    $.ajaxSetup({
        "error": function (XMLHttpRequest, textStatus, errorThrown) {
            if(XMLHttpRequest.status == 403) {
                display_modal( 'Please login to continue.', 'Session in closed.');
                //XMLHttpRequest.abort();
            }
        }
    });

防止来自未经身份验证的用户的ajax请求。

但在特定视图中,当发出POST / GET请求时我有

   var posting = $.post(
            post_url, 
            $("#" + form).serialize(),
            function(data) {
                packet = data;
            },
            'json'
    );
    posting.done(function() { 
        form_post_response_function(e, packet); 
    });
    posting.fail(function() {
        var packet = {};
        packet.data = {};
        packet.data.type = "Ajax Post Fail";
        packet.status = -200;
        packet.statusMessage = "ERROR";
        form_post_response_function(e, packet); 
    });

我原本期望posting.fail(function() {getting.fail(function() {不被调用。但它们是,所以所有的流程都会进行,并以另一个模式重叠403消息结束。

如果没有原始$.ajax,我该如何避免这种情况?如何阻止JQuery在错误捕获时流动?

最终代码

posting.fail(function(jqXHR, textStatus, errorThrown) {
    if(jqXHR.status != 403) {
        var packet = {};
        packet.data = {};
        packet.data.type = "Ajax Post Fail";
        packet.status = -200;
        packet.statusMessage = "ERROR";
        form_post_response_function(e, packet); 
} else {
           // event also can be accessed here
           $(get_target(e)).button('reset');
    }
});

然后轻轻地停下来。看起来不错。

2 个答案:

答案 0 :(得分:0)

抛出异常以停止执行更多代码。

例如:throw "stop execution here";

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw

答案 1 :(得分:0)

查看所有详细信息的问题

这是最终代码

posting.fail(function(jqXHR, textStatus, errorThrown) {
    if(jqXHR.status != 403) {
        var packet = {};
        packet.data = {};
        packet.data.type = "Ajax Post Fail";
        packet.status = -200;
        packet.statusMessage = "ERROR";
        form_post_response_function(e, packet); 
} else {
           // event also can be accessed here
           $(get_target(e)).button('reset');
    }
});