2015-02-07 191 views
2

我的Ajax代码是:AJAX就绪状态reachs 4,但状态始终是200

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和铬和ie,但在safari我总是得到状态200. 我使用safari 5.1.7。我也使用response.setStatus而不是response.sendError,但它不起作用。有人知道为什么会发生这种情况吗?

回答

3

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

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

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

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

您可能想要使用HttpServletResponse#setStatusHttpServletResponse#sendError来这样做。

或者您可能想要在web.xml中定义一个错误页面。退房:How to set HTTP status code in JSP error handlers

1

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

总之,不应该使用http响应的状态码发送自己的状态码,因为它违反了协议,并可能导致中间件服务器(如高速缓存服务器)出现问题。