javascript - AJAX + JSON for simple login -
i new ajax , json i'm looked tutorials seems that dept me.
i decided make simple login see how ajax , json works don't know how start. said need library jars
, said javasrcipt
here simple login jsp page
<body> <form action="logincontroller" method="post"> <!-- login body --> <table> <tr> <td><label for="username" >username:</label></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><label for="password" >password:</label></td> <td><input type="password" name="password" /></td> </tr> <tr> <td><input type="submit" /></td> </tr> </table> </form> </body>
how apply json
+ ajax
wouldn't refresh if user doesn't enter proper username , password
by way here's controller:
userdao userdao = new userdao(); // instantiate dao class access dummy database string username = request.getparameter( "username" ); // username string login.jsp string password = request.getparameter( "password" ); // password string login.jsp if( userdao.authenticate( username, password ) ) // validate username , password { usermodel usermodel = userdao.getuserdetails( username ); // usermodel correspond username parameter request.getsession().setattribute( "username", username ); // set session request forward mainpage.jsp request.setattribute( "userdetails", usermodel ); // set request forward mainpage.jsp requestdispatcher rd = request.getrequestdispatcher( "mainpage.jsp" ); rd.forward( request, response ); // forward request mainpage.jsp return; } else { response.sendredirect( "login.jsp" ); return; }
json data structure javascript objects formatted in. if using jquery correct way send request via ajax use either $.ajax function or $.post function in case.
$('input[type="submit"]').click(function(e){ e.preventdefault(); var action_script = $(this).closest('form').prop('action'); $.post(action_script, {username : $(this).closest('form').find('input[name="username"]'), password: $(this).closest('form').find('input[name="password"]')}, function(returned_data){ //this part executes once server returns successful response }); });
this binds handler click event of submit button stop normal post occuring result in page refresh. $.post() post data username , password server , execute success callback when response sent back.
{username : $(this).closest('form').find('input[name="username"], password: $(this).closest('form').find('input[name="password"]')}
example of json. simple json object 2 attributes username , password. set of key value pairs , such can treated associative array.
when ajax request made response not force re render of page have handle resultant data in callback method of $.post()
http://api.jquery.com/jquery.ajax/ more information on how .ajax method in jquery works
Comments
Post a Comment