开发者

Display different result in different html div

开发者 https://www.devze.com 2023-02-21 15:47 出处:网络
This is my js file in which I am using jquery to verify login problem: how can I differentiate the result in login_process.jsp i.e if the message is out.println\"(Please Enter your Email)\" I want to

This is my js file in which I am using jquery to verify login problem: how can I differentiate the result in login_process.jsp i.e if the message is out.println"(Please Enter your Email)" I want to print it in div id =targetDiv and if the msg is msg.indexOf("Please Enter your Password") I want to print it in div id= targetDiv2if both the fields are empty then above listed messages should appear in respective divs but none of them are displaying

How can I do this in jquery

hi again i have created a servlet given below                                                                           protected voi开发者_StackOverflow中文版d 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;
  });
});


  1. Obligatory note: Don't use JSPs for business logic, they're best suited as 'dumb' views that simply display the data they're passed. Any such logic should go into a servlet.

  2. Your Java code could be written to better follow the code-conventions.

  3. You can return a JSON object/array indicating the selector for jQuery along with the message to be displayed. Something like:

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

    It's probably best to use a library to generate the JSON because doing it by hand is going to be error-prone and not very extensible. If you choose to use the JSON.org library, this is what you can add to your Servlet (please note you will have to download the library and add it to your project classpath and import it into your code to be able to use it - just like with any other Java library :

    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. The JavaScript for this will be something of the form:

    $.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?
                        }
                    }
    });
    

    Note that it's better to send the data as an object to .ajax() rather than try and create the query string yourself.

  5. If you choose to continue doing it the way shown in the example code you've posted, note that you're expecting indexOf to return 0 for both messages. This will only work when there's only one message. This will fail for the second message when both are returned. It is also the reason why you're seeing both messages in the same div because when you find one message, you print out the whole string (msg) into one div. So when you find the message for the username, you end up printing the entire msg string, which includes both messages, into the div targetDiv. The other check fails. I would suggest you drop this way completely.


Ahsan ,

You should clean up your code , all the backend should do is to get the status back.

Assume the above scenario , your jsp file should process the login and password and just send the status back to the UI sayings its success or failure

you should say

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

maintain a hidden P or div and just show the message.

0

精彩评论

暂无评论...
验证码 换一张
取 消