2015-10-09 75 views
1

我使用,servlet創建登錄頁面,但我似乎無法讀取返回的響應,當響應爲真時,它必須轉到success.jsp頁面,但它不會,我不確定我做錯了什麼,請幫忙。 這裏我:jQuery成功功能不返回來自servlet響應的消息

JS

$.ajax({ 
     url: "LoginServlet", 
     type: "post", 
     data: { 
     "username": username, 
     "password": password 
     }, 
     cache: false, 
     success: function(data) { 
     var xhr = data.msg; 
     if (xhr === "true") { 
      alert(xhr); 
      window.location.href = "success.jsp"; 

     } else { 
      alert(xhr); 
     } 
     } 

我的servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ 
     LoginDAO dao = new LoginDAO(); 
     String username=request.getParameter("username"); 
     String password=request.getParameter("passsword"); 
     String msg = "false"; 




     Login login = dao.validateUser(username, password); 

      String username1 = login.getUsername(); 
      String password1 = login.getPassword(); 
     if(LoginDAO.isEqual(username, password1) && LoginDAO.isEqual(password, password1)){ 

       msg = "true"; 

     } 


     response.setContentType("text/plain"); 
     response.getWriter().write(msg); 


    } 
+0

$(文件)。就緒(函數(){ \t $( '#btnlogin' )。單擊(函數(e)中{ \t \t \t \t 變種\t用戶名= $( '#用戶名')VAL(); \t \t var password = $('#password')。val(); \t \t \t \t \t $阿賈克斯({ \t \t \t網址: 「LoginServlet」, \t \t \t類型: 「後」, \t \t \t數據:{ 「用戶名」:用戶名, 「密碼」:密碼}, \t \t \t緩存:假的, \t \t \t成功:功能(數據){ \t \t \t \t var xhr = data.msg; \t \t \t \t如果(XHR === 「真」){ \t \t \t \t \t警報(XHR); \t \t \t \t window.location.href =「success。JSP」; \t \t \t \t \t \t \t} \t \t \t別的 \t \t \t \t { \t \t \t \t警報(XHR); \t \t \t \t} \t \t \t} \t \t}); \t \t}); }); – user3576758

+1

請編輯該問題;不要將太多的代碼放入評論中。 –

+0

在您的js代碼中添加一個錯誤回調,以查看是否已達到... – n00dl3

回答

0

在你的代碼,這個代碼:

response.setContentType("text/plain"); 
response.getWriter().write(msg); 

設置響應類型text/plain的值爲:truefalse

然後,在您的jQuery.ajax()函數中更改var xhr = data.msg;var xhr = data;

$.ajax({ 
    url: "LoginServlet", 
    type: "post", 
    data: { 
     "username": username, 
     "password": password 
    }, 
    dataType: "text", // To match with the actual response type: «text/plain». 
    cache: false, 
    success: function (data) { 
     var xhr = data; // Because «data» contains true or false. 
     if (xhr === "true") { 
      alert(xhr); 
      window.location.href = "success.jsp"; 

     } else { 
      alert(xhr); 
     } 
    } 
}); 
+0

謝謝@Danny它顯示的消息和重定向的基礎上的數據.. – user3576758

+0

不客氣@ user3576758。 –

1

我已經直接分配的用戶名密碼&,但你應該從UI得到它們。 如下修改您的客戶端代碼:

你拼錯密碼密碼時應請更正

String username = request.getParameter("username"); 
String password = request.getParameter("password"); 
+0

非常感謝@Ashish認爲真的讓我擺脫了壓力... – user3576758

+0

最受歡迎... –

+0

@ user3576758如果它能幫助你解決問題,那麼你應該接受和滿意答案 –