如果在特定时间后未返回ajax响应,如何显示错误

时间:2017-04-12 06:50:36

标签: jquery ajax response

如何确保由于某些错误而未发送Ajax响应?当加载器继续加载时,如何确保在特定时间后向用户显示某些消息?这就是我想要的。

  jQuery.ajax({

        type: "POST",
        url:url,
        data:{id:id},

        beforeSend:function() {
            //loader()
        },
        success: function(msg) {

           // sucess
        }
    });

3 个答案:

答案 0 :(得分:3)



jQuery.ajax({

        type: "POST",
        url:url,
        data:{id:id},

        beforeSend:function() {
            //loader()
        },
        success: function(msg) {

           // sucess
        },
        error: function (jqXHR, exception) {
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'Not connect.\n Verify Network.';
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
        },
        timeout: 5000 // sets timeout to 3 seconds
    });




答案 1 :(得分:2)

试试此代码

jQuery.ajax({
        type: "POST",
        url:url,
        data:{id:id,type:type},
        timeout:5000 //This will set timeout to 5 seconds
        beforeSend:function() {
             // loader
        },
        success: function(msg) {

          // Success

        },
        error: function(){
           // It will fire once timeout is reached
           // If you have any other error in the code
           // like wrong function name etc,keep it mind timeout 
           // function wouldn't work,and you will see the error without 
           // waiting for the timeout function.

        })};

顺便说一句,你可以获得@alok提到的所有错误列表。

答案 2 :(得分:1)

您可以在错误回调中设置超时选项句柄错误。

$.ajax({
url: "test.html",
error: function(){
    // will fire when timeout is reached
},
success: function(){
    //do something
},
timeout: 3000 // sets timeout to 3 seconds
});