Ajax实例练习:
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//作业面局部刷新,不做页面跳转的时候,推荐使用ajax
$("#login").click(function(){
//点击按钮实现登录功能
/* $.ajax({
type:'post', //type:请求方式,get,post
url:'login.action', //要访问的后台地址
data:{
'uname':$("#uname").val(),
'pwd':$("#pwd").val()
},
success:function(result) {
if(result=='1') {
//1.welcome
location.href="welcome.jsp";
} else {
//2.login
$("#tip").show();
}
}
}); */
/* $.post('login.action',{
'uname':$("#uname").val(),
'pwd':$("#pwd").val()
},function(result){
//回调函数:当后台成功响应结果时,会自动调用
if(result=='1') {
//1.welcome
location.href="welcome.jsp";
} else {
//2.login
$("#tip").show();
}
}); */
$.get('login.action?uname='+$("#uname").val()+'&pwd='+$("#pwd").val(),function(result){
//回调函数:当后台成功响应结果时,会自动调用
if(result=='1') {
//1.welcome
location.href="welcome.jsp";
} else {
//2.login
$("#tip").show();
}
});
})
})
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
body之中的内容:
<body>
<table>
<tr>
<td>用户名:</td>
<td>
<input type="text" id="uname">
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" id="pwd">
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="登录" id="login">
</td>
</tr>
</table>
<span id="tip" style="color: red;display: none;">用户名或密码错误</span>
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
LoginServlet.java中的doPost()方法:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String uname=request.getParameter("uname");
String pwd=request.getParameter("pwd");
System.out.println(uname);
//1.登录成功
//2.登录失败
if("admin".equals(uname)&&"123".equals(pwd)) {
//welcome
out.print("1");
} else {
//login
out.print("2");
}
out.flush();
out.close();
}