在不同的html div中显示不同的结果

时间:2011-04-03 21:32:04

标签: jquery

这是我的js文件,我在其中使用jquery来验证登录 问题:如何区分login_process.jsp中的结果,即如果消息是out.println“(请输入您的电子邮件)”我想在div id =targetDiv打印它,如果消息是msg.indexOf("Please Enter your Password")我想要在div id= targetDiv2中打印它,如果两个字段都是空的,那么上面列出的消息应该出现在相应的div中但是没有一个显示

如何在jquery

中执行此操作
hi again i have created a servlet given below                                                                           protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet loginServlet</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet loginServlet at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
        */
        String uname= request.getParameter("user");
        String pass= request.getParameter("pass");
       if (uname.isEmpty())
       {
           response.setContentType("text/plain");
           response.setCharacterEncoding("UTF-8");
           response.getWriter().println("Please Enter Your Username");
       }
        if (pass.isEmpty())
       {
           response.setContentType("text/plain");
           response.setCharacterEncoding("UTF-8");
           response.getWriter().println("Please Enter Your Password");
       }
    } finally { 
        out.close();
    }
}                                                                           it has started to display messages in the div but unfortunately both of them appear in the same div as if they were a single message                                                                      i have also used response.getWriter().write() but in that case both messages appear as single line in   both  divs i know this is not the method u advised above can u help with it or add code lines the way u think it should be

//loginvalidate.js
$(document).ready(function(){
  //global vars
  var userName = $("#user"); //user name field
  var userPass = $("#pass"); //password field

//function to check name and comment field
  function checkCommentsForm(){
    //if(userName.attr("value") && userPass.attr("value"))
      return true;
    //else
      //return false;
  }

  //When form submitted
  $("#formL").submit(function(){

if(checkCommentsForm()){

      $.ajax({
        type: "post"
       , url: "loginProcess.jsp"
       ,data: "user="+userName.val()+"&pass="+userPass.val(),
       success: function(msg) {$('#targetDiv').hide();


           if(msg.indexOf("Please Enter your UserName") == 0){
           $("#targetDiv").html ("<h3>" + msg + "</h3>").fadeIn("slow");}

      if(msg.indexOf("Please Enter your Password") == 0){
            $("#targetDiv2").html ("<h3>" + msg + "</h3>").fadeIn("slow");
        }
       }

    });
        }
    else alert("Please fill UserName & Password!");
    return false;
  });
});

2 个答案:

答案 0 :(得分:0)

Ahsan,

你应该清理你的代码,所有后端应该做的是恢复状态。

假设上面的场景,你的jsp文件应该处理登录名和密码,然后将状态发回给UI说明成功或失败

你应该说

if(msg.Response.Status=="Success"){
}
else{
}

维护隐藏的P或div,只显示消息。

答案 1 :(得分:0)

  1. 强制性说明:不要将JSP用于业务逻辑,它们最适合作为“哑”视图,只显示它们传递的数据。任何这样的逻辑都应该进入servlet。

  2. 您的Java代码可以编写为更好地遵循code-conventions

  3. 您可以返回一个JSON对象/数组,指示jQuery的选择器以及要显示的消息。类似的东西:

    [{"selector": "#targetDiv", "msg": "Please Enter Your Username"}, {"selector":"#targetDiv2", "msg":"Please Enter Your Password"}]
    

    最好使用library来生成JSON,因为手动执行它会容易出错,而且不是很容易扩展。如果您选择使用JSON.org库,那么您可以将其添加到Servlet中(请注意,必须下载库并将其添加到项目类路径并将其导入到您的代码中能够使用它 - 就像任何其他Java库一样:

    JSONArray messages = new JSONArray();
    if(uname == null || uname.isEmpty())
    {
        JSONObject msg = new JSONObject();
        msg.put("selector", "#targetDiv");
        msg.put("msg", "Please Enter Your Username");
        messages.put(msg);
    }
    
    if(pass == null || pass.isEmpty())
    {
        JSONObject msg = new JSONObject();
        msg.put("selector", "#targetDiv2");
        msg.put("msg", "Please Enter Your Password");
        messages.put(msg);
    }
    
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().println(messages.toString());
    
  4. 这方面的JavaScript将是以下形式:

    $.ajax({
            type: "post",
            url: "loginProcess.jsp",
            data: {user : userName.val(), pass : userPass.val()},
            success: function(data) {
                        if(data && data.length) { //expecting an array of error messages
                        //get each message and set it as the HTML for it's selector and fade in
                            for(var i = 0; i < data.length; i++){
                                $(data[i].selector).html(data[i].msg).fadeIn('slow');
                            }
                        }
                        else {
                            //successful login?
                        }
                    }
    });
    

    请注意,最好将数据作为对象发送到.ajax(),而不是自己尝试创建查询字符串。

  5. 如果您选择按照发布的示例代码中显示的方式继续操作,请注意您希望indexOf为这两封邮件返回0。这仅在只有一条消息时才有效。返回两者时,第二条消息将失败。这也是你在同一个div中看到这两个消息的原因,因为当你找到一条消息时,你将整个字符串msg)打印成一个div。因此,当您找到用户名的消息时,您最终会将整个msg字符串(包括这两封消息)打印到div targetDiv中。另一项检查失败。我建议你完全放弃这种方式。