2012-05-04 41 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(); –