【问题标题】:detecting HTTP error using ajax使用ajax检测HTTP错误
【发布时间】:2012-02-15 18:05:09
【问题描述】:

我正在使用 ajax 调用来检索一些 HTML 数据。在某些情况下,我可能会收到 HTTP 错误 403(由于一些 IE 错误Encountering 403 error while using ajax call on IEHash fragments with forward-slash throwing 403 errors with AJAX requests in IE)。

出于错误处理的目的,我想捕捉发生了什么错误并相应地显示一些错误消息。

我该怎么做?

可能是这样的

$.ajax({
    type : 'POST',
    data : data,
    cache : false,
    url : url,
    dataType : 'html'
    success : function(){
        //if HTTP response is ok, diplay data
        //else if HTTP response gets 403 error, display some other message
    }
});

【问题讨论】:

    标签: ajax internet-explorer error-handling http-status-code-403 http-error


    【解决方案1】:

    引用documentation

    错误(jqXHR,textStatus,errorThrown)
    功能
    请求失败时调用的函数。
    该函数接收三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象、描述发生的错误类型的字符串和可选的异常对象(如果发生)。第二个参数的可能值(除了 null)是“timeout”、“error”、“abort”和“parsererror”。发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。从 jQuery 1.5 开始,错误设置可以接受一个函数数组。每个函数都会被依次调用。注意:跨域脚本和 JSONP 请求不会调用此处理程序。

    $.ajax({
        type : 'POST',
        data : data,
        cache : false,
        url : url,
        dataType : 'html'
        success : function(){
            //if HTTP response is ok, diplay data
            //else if HTTP response gets 403 error, display some other message
        },
        error: function(){
            // Handle your error here
        }
    });
    

    【讨论】:

    • 谢谢。现在可以了。您能否指出与同一文档页面中的 statusCode 处理程序有什么区别?看来你可以使用类似statusCode: { 404: function() { alert('page not found'); }
    猜你喜欢
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2011-05-22
    • 2013-02-12
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多