简体   繁体   中英

Pass multiple objects from servlet to Javascript file using ajax call

In my login servlet page have some conditions.The user is registered user pass URL to JavaScript using ajax call. If the user is not registered then try to login i need to display error message and redirect to same page URL but here i am unable to pass both URL and message at a time to JavaScript file using ajax call i am able to pass only one object either URL or message anyone please tell me how to pass both objects to JavaScript.

This happens Because print(arg) of Class PrintWriter that you referred by out only accepts one single argument. be it of any type. view API here . Assuming that you always get a success callback. try should work:

code:

String resp= "";    // final response
if(User.isValid())
{                  
    resp="MyList.jsp" ;
}
else
{
    Url="Login.jsp";
    Msg="Sorry, you are not a registered user! Please sign up first";
    resp= Url + "@" + Msg;
}
PrintWriter out = response.getWriter();
out.print(resp); // based upon your condition above.

change your JS:

<script type="text/javascript">
    $(document).ready(function() {
        $('#btnLogin').click(function ()
        {
            $.ajax({
                type: "post",
                url: "Login", //this is my servlet
                data: "uname=" +$('#inputUserID').val()+"&pwd="+$('#inputPassword').val(),

                success: function(data){
                    alert(data);
                    var response = data.split("@");
                    if(response.length>1){
                        // if user is a valid user
                        $(window.location).attr('href', response[0]);
                    } else {
                        // if user in invalid
                        $(window.location).attr('href', response[0]);
                        $("#message").html(response[1]);
                    }
                }
            });
        });
    });
</script>

You can concatenate the Strings of URL and MSG and pass in out.println with a delimiter and then split the same at other end in JS.

  if
  {
      data ="Login.jsp$Sorry, you are not a registered user! Please sign up 
      first";
   }
   PrintWriter out = response.getWriter();
   out.print(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM