2

我的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。我使用 safari 5.1.7。我也使用response.setStatus而不是,response.sendError但它不起作用。有人知道为什么会这样吗?

4

2 回答 2

3

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

AJAX 客户端将获得响应并将状态代码存储在xhr.status上。

它应该是一个有效的HTTP 状态码

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

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

或者您可能想在 web.xml 上定义一个错误页面。查看:如何在 JSP 错误处理程序中设置 HTTP 状态代码

于 2015-02-07T08:33:50.170 回答
1

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

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

于 2015-02-07T08:35:52.920 回答