2012-05-04 42 views
1

我正在使用Servlet作为控制器和jQuery向服务器发送请求。以下是我的jQuery请求如何获取HTTP状态码和消息使用jquery

$.post("login", {userName:$userName, password:$password}, function(data, textStatus) { 
alert(textStatus); 
}); 

而在服务器端我写了下面的代码

response.setContentType("text/plain"); 
      PrintWriter out = response.getWriter(); 
      out.println("" + strError + ""); 
      out.flush(); 
      out.close(); 

我想设置错误信息和错误错误状态代码在servlet和读取的jQuery相同的状态代码。我怎样才能达到相同的目标?

回答

0

您可以从服务器返回一个json编码的字符串。 How do you return a JSON object from a Java Servlet

例如,如果您发回以下json编码的字符串。 {“错误”:“这是一些错误信息”}在客户端,你会做以下

$.post("login", {userName:$userName, password:$password}, function(data, textStatus) { 
    alert(data.error); // your error message will show up here in the data object 
},'json'); 
0

在一个Java servlet,设置HTTP状态

然后,你必须使用以下内容:

response.setStatus(code); 

code部分可以是几件事情像HttpServletResponse.SC_NOT_FOUND效仿错误404(找不到页面)。详尽的清单可以在here找到。

在jQuery的一面,你可以使用以下命令:

$.post('login', { /* ... */ }, function(data, textStatus, xhrObject) { 
    // You can read the status returned with 
    xhrObject.status; 
}); 

我猜textStatus变量保存状态,但documentation并没有说什么它可以返回任何东西。

+0

如果我在servlet中设置状态,我没有在jquery中获得状态码。我按照你现在的建议做了同样的事情。 –

+0

您试图在调试器中看到'textStatus'变量的内容? 'xhrObject'是一样的吗? –

+0

如果我设置了状态码,调试器不会进入该功能。如果我不设置状态码,那么它显示状态码为200.我已经在servlet response.setStatus(response.SC_BAD_REQUEST)中写入了以下内容; response.setContentType(“text/plain”); PrintWriter out = response.getWriter(); out.println(“”+ strError +“”); out.flush(); out.close(); –