我的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 和 IE,但在 Safari 中我总是得到状态 200。
我使用 Safari 5.1.7。我还使用 response.setStatus
而不是 response.sendError
但它不起作用。
有人知道为什么会发生这种情况吗?
最佳答案
您需要在 servlet 上设置响应服务器端的状态。
AJAX 客户端将获取响应并将状态代码存储在 xhr.status 上.
它应该是有效的 HTTP status code .
不要忘记在提交响应和发送任何 header 之前必须设置响应代码。
您可能想使用HttpServletResponse#setStatus或HttpServletResponse#sendError这样做。
或者您可能想在 web.xml 上定义一个错误页面。查看:How to set HTTP status code in JSP error handlers
关于ajax 就绪状态达到 4 但状态始终为 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380100/