首页 文章

JQuery Ajax - 如何在进行Ajax调用时检测网络连接错误

提问于
浏览
75

我有一些Javascript JQuery代码,每5分钟对服务器进行一次Ajax调用,它在JQuery中使用 $.ajax() 方法's to keep the server session alive and keep the user logged in. I'm . 此函数似乎有一个'error'属性,我'm trying to use in the event that the user'的互联网连接断开,以便KeepAlive脚本继续运行 . 我正在使用以下代码:

var keepAliveTimeout = 1000 * 10;

function keepSessionAlive()
{
    $.ajax(
    {
        type: 'GET',
        url: 'http://www.mywebapp.com/keepAlive',
        success: function(data)
        {
            alert('Success');

            setTimeout(function()
            {
                keepSessionAlive();
            }, keepAliveTimeout);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert('Failure');

            setTimeout(function()
            {
                keepSessionAlive();
            }, keepAliveTimeout);
        }
    });
}

当我运行它时,我会在屏幕上每10秒钟在一个警告框中弹出“成功”,这很好 . 但是,一旦我拔下网线,我就什么也得不到,我期待错误功能被调用并看到“故障”警告框,但没有任何反应 .

假设'错误'功能仅适用于从服务器返回的非'200'状态代码,我是否正确?有没有办法在进行Ajax调用时检测网络连接问题?

8 回答

  • -1
    // start snippet
    error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.readyState == 4) {
                // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
            }
            else if (XMLHttpRequest.readyState == 0) {
                // Network error (i.e. connection refused, access denied due to CORS, etc.)
            }
            else {
                // something weird is happening
            }
        }
    //end snippet
    
  • 1

    你应该在 $.ajax({}) 内的某处添加: timeout: <number of miliseconds>, . 此外, cache: false, 可能在某些情况下有所帮助 .

    $.ajax is well documented,你应该检查那里的选项,可能会找到有用的东西 .

    祝好运!

  • -4

    由于我无法复制该问题,我只能建议尝试在ajax调用上超时 . 在jQuery中,您可以使用$ .ajaxSetup设置它(并且它将是所有$ .ajax调用的全局),或者您可以专门为您的调用设置它,如下所示:

    $.ajax({
    type: 'GET',
    url: 'http://www.mywebapp.com/keepAlive',
    timeout: 15000,
    success: function(data) {},
    error: function(XMLHttpRequest, textStatus, errorThrown) {}
    })
    

    jQuery会在你的通话中注册15秒超时;之后,如果没有来自服务器的http响应代码,jQuery将执行错误回调,并将textStatus值设置为“timeout” . 有了这个,你至少可以停止ajax调用,但是你无法区分真正的网络问题和连接丢失 .

  • 82

    我在这种情况下看到的是,如果我拉客户端机器的网络电缆并进行调用,则会调用ajax成功处理程序(为什么,我不知道),并且data参数是一个空字符串 . 因此,如果您将真正的错误处理分解出来,您可以执行以下操作:

    function handleError(jqXHR, textStatus, errorThrown) {
        ...
    }
    
    jQuery.ajax({
        ...
        success: function(data, textStatus, jqXHR) {
            if (data == "") handleError(jqXHR, "clientNetworkError", "");
        },
        error: handleError
    });
    
  • 3

    如果您正在跨域调用Use Jsonp . 否则不会返回错误 .

  • 13

    使用

    xhr.onerror = function(e){
        if (XMLHttpRequest.readyState == 4) {
            // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
            selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
        }
        else if (XMLHttpRequest.readyState == 0) {
            // Network error (i.e. connection refused, access denied due to CORS, etc.)
            selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
        }
        else {
            selFoto.erroUploadFoto('Erro desconhecido.');
        }
    
    };
    

    (更多代码 - 上传图片示例)

    var selFoto = {
       foto: null,
    
       upload: function(){
            LoadMod.show();
    
            var arquivo = document.frmServico.fileupload.files[0];
            var formData = new FormData();
    
            if (arquivo.type.match('image.*')) {
                formData.append('upload', arquivo, arquivo.name);
    
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
                xhr.responseType = 'blob';
    
                xhr.onload = function(e){
                    if (this.status == 200) {
                        selFoto.foto = this.response;
                        var url = window.URL || window.webkitURL;
                        document.frmServico.fotoid.src = url.createObjectURL(this.response);
                        $('#foto-id').show();
                        $('#div_upload_foto').hide();           
                        $('#div_master_upload_foto').css('background-color','transparent');
                        $('#div_master_upload_foto').css('border','0');
    
                        Dados.foto = document.frmServico.fotoid;
                        LoadMod.hide();
                    }
                    else{
                        erroUploadFoto(XMLHttpRequest.statusText);
                    }
    
                    if (XMLHttpRequest.readyState == 4) {
                         selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
                    }
                    else if (XMLHttpRequest.readyState == 0) {
                         selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);                             
                    }
    
                };
    
                xhr.onerror = function(e){
                if (XMLHttpRequest.readyState == 4) {
                    // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
                    selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
                }
                else if (XMLHttpRequest.readyState == 0) {
                     // Network error (i.e. connection refused, access denied due to CORS, etc.)
                     selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
                }
                else {
                    selFoto.erroUploadFoto('Erro desconhecido.');
                }
            };
    
            xhr.send(formData);
         }
         else{
            selFoto.erroUploadFoto('');                         
            MyCity.mensagens.push('Selecione uma imagem.');
            MyCity.showMensagensAlerta();
         }
      }, 
    
      erroUploadFoto : function(mensagem) {
            selFoto.foto = null;
            $('#file-upload').val('');
            LoadMod.hide();
            MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
            MyCity.showMensagensAlerta();
     }
     };
    
  • 0

    这是我在网络出现故障或页面更新失败时提醒用户的行为:

    • 我在页面上有一个div-tag,我将当前时间设置为每隔10秒更新一次 . 它看起来像这样: <div id="reloadthis">22:09:10</div>

    • 在更新div-tag中的时间的javascript函数结束时,我把它(在使用AJAX更新时间之后):

    var new_value = document.getElementById('reloadthis').innerHTML;
    var new_length = new_value.length;
    if(new_length<1){
        alert("NETWORK ERROR!");
    }
    

    而已!当然,您可以将警报部分替换为您想要的任何内容 . 希望这可以帮助 .

  • 9

    你试过这个吗?

    $(document).ajaxError(function(){ alert('error'); }
    

    这应该处理所有AjaxErrors . 我发现它here . 在那里,您还发现可以将这些错误写入您的firebug控制台 .

相关问题