发生错误时未调用jQuery AJAX错误回调

时间:2016-09-01 14:48:47

标签: javascript jquery ajax

我目前正在尝试从我的服务器实现 HTTP 413:请求实体太大错误的处理。我所做的就是:

$.ajax({
    url: "submit.php",
    data: {
        "data": POSTData
    },
    success: function(response, statusText, XHR) {
        console.log(XHR.status + ": " + response);
        resolve(); // resolve the promise and continue on with execution
    },
    // Added this part:
    error: function(response, statusText, XHR) {
        if(XHR.status === 413) {
            // Request entity too large
            // To solve this we split the data we want to upload into several smaller partitions
            // and upload them sequentially

            console.log("Error 413: Request entity too large. Splitting the data into partitions...");

            // handling code below

            // blahblahblah
        }
    },
    method: "POST"
});

但是没有触发错误回调,我的控制台仍然会抛出错误(它表示它是413),好像没有处理程序。如何实现此功能?

2 个答案:

答案 0 :(得分:3)

您错误回调的方法签名错误。见http://api.jquery.com/jquery.ajax/

根据这些文档的正确签名是: 函数(jqXHR jqXHR,String textStatus,String errorThrown)

因此,在您的情况下,XHR.status不存在,因为您所谓的XHR实际上是一个字符串。

试试这个:

float xPercent = 30; //for example you want a 30% decrease
[self.dullViewHeight setConstant: self.colouredView.frame.size.height*(1-(xPercent/100))];

我强烈怀疑错误回调正在被调用,但由于您在if语句之外没有任何代码,因此您没有看到任何内容。

答案 1 :(得分:1)

您只能在一个地方使用jQuery.ajaxSetup()处理此类错误。这样您就可以处理HTTP 413以上的错误。

代码:

$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                console.log('Not connect.n Verify Network.');
            } else if (jqXHR.status == 404) {
                console.log('Requested page not found. [404]');
            } else if (jqXHR.status == 413) {
                console.log('Error [413]: Request entity too large. Splitting the data into partitions...');
            } else if (jqXHR.status == 500) {
                console.log('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                console.log('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                console.log('Time out error.');
            } else if (exception === 'abort') {
                console.log('Ajax request aborted.');
            } else {
                console.log('Uncaught Error.n' + jqXHR.responseText);
            }
        }
    });
});