【问题标题】:ajax ready state reachs 4 but status always is 200ajax 就绪状态达到 4 但状态始终为 200
【发布时间】:2015-02-07 08:29:53
【问题描述】:

我的 ajax 代码是:

 xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.status);
        if (xhr.status == 200) {
            alert("200");               
        }
        else if (xhr.status == 8001) {
            alert("8001");               
        }
        else if (xhr.status == 8000) {
            alert("8000");             
        }
        else if (xhr.status == 7000) {
            alert("7000");                
        }
        else {
            alert("x");              
        }
    }
};
xhr.open("POST","URL",true);
xhr.send(null);

我在 xhr.open 中处理的页面中的代码是:

    if (request.getSession().getAttribute("SATI_UID") == null) {
        response.sendError(8000);
    } else {
            response.sendError(8001);
    }

它可以在 firefox 和 chrome 中工作,但在 safari 中我总是得到状态 200。 我使用野生动物园 5.1.7。我也使用response.setStatus 而不是response.sendError,但它不起作用。 有人知道为什么会这样吗?

【问题讨论】:

    标签: ajax jsp servlets safari onreadystatechange


    【解决方案1】:

    您需要在您的 servlet 上设置响应服务器端的状态。

    AJAX 客户端将获取响应并将状态码存储在xhr.status

    它应该是一个有效的HTTP status code

    不要忘记必须在提交响应和发送任何标头之前设置响应代码。

    您可能希望使用HttpServletResponse#setStatusHttpServletResponse#sendError 来执行此操作。

    或者您可能想在您的 web.xml 上定义一个错误页面。签出:How to set HTTP status code in JSP error handlers

    【讨论】:

      【解决方案2】:

      我认为这是因为您使用了非标准的 http 法规。您应该抛出正确类型的错误 4xx 或 5xx(参见 http status codes),因为此代码在 HTTP protocol 中具有真正的含义,然后在响应正文中为您的错误设置您自己的自定义代码。

      总而言之,不应该使用 http 响应的状态码来发送您自己的状态码,因为它会破坏协议并可能导致中间件服务器出现问题(例如缓存服务器)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-14
        • 2011-03-16
        • 2021-07-10
        • 2011-03-05
        • 1970-01-01
        相关资源
        最近更新 更多