1.使用Ajax实现异步操作,点击登录按钮后,即触发form表单的提交事件,数据传输至后端
JSP:
<script type="text/javascript" src="resources/js/jquery.js"></script> <script type="text/javascript" src="resources/js/login.js"></script> <form id = "form"> <table align = "center"> <tr> <td>用户名</td><td><input type = "text" id = "userName" name = "userName"></td> </tr> <tr> <td>密码</td><td><input type = "password" id = "userPwd" name = "userPwd"></td> </tr> <tr> <td align = "left"><input id = "submitbtn" type = "submit" value = "登录" style = "background-color: Cyan;color:blue"></td> <td align = "right" ><button style = "background-color: Cyan;color:blue"><a href = "/SSM/user/toRegister">注册</a></button></td> </tr> </table> </form>
js:
1 $(function(){ 2 $("#submitbtn").click(function(){ 3 login(); 4 }) 5 }) 6 function login(){ 7 var userName = $("#userName").val();//获取userName的值 8 var userPwd = $("#userPwd").val();//获取userPwd的值 9 $.ajax({ 10 url:"user/judgeLogin", 11 type:"POST", 12 data:{"userName":userName,"userPwd":userPwd}, 13 dataType:"json",
14 success:function(returnData){
15 alert(returnData);
16 }
17 })
18 }
js另一种传值方法:
1 function login(){ 2 $.ajax({ 3 url:"user/judgeLogin", 4 type:"POST", 5 data:$("#form").serialize(),//表单序列化 6 dataType:"json", 7 success:function(returnData){ 8 alert(returnData); 9 } 10 }) 11 }
Controller层 接收:
1 /** 2 * 登录判断 3 * @param userDto 4 * @return 5 */ 6 @ResponseBody 7 @RequestMapping("/judgeLogin") 8 public String judgeLogin(UserDto userDto) { 9 int k = userService.judgeLogin(userDto); 10 if(k > 0) { 11 return "--登录成功!--"; 12 }else { 13 return "--登录失败!--"; 14 } 15 }
效果展示: