在使用form表单的时候,一旦点击提交触发submit事件,一般会使得页面跳转,页面间的跳转等行为的控制权往往在后端,后端会控制页面的跳转及数据传递,但是在某些时候不希望页面跳转,或者说想要将控制权放在前端,通过js来操作页面的跳转或者数据变化。一般这种异步的操作,我们都会想到Ajax方式,因此在实现了功能后就整理了这篇文章,通过Ajax方式实现form表单的提交并进行后续的异步操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="login test">
</head>
<body>
<div id="form-div">
<form id="form1" action="/users/login" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p>
<p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p>
<p><input type="submit" value="登录"> <input type="reset" value="重置"></p>
</form>
</div>
</body>
</html>
|
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
| <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="ajax方式">
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function login() {
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/users/login" ,//url
data: $('#form1').serialize(),
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
alert("SUCCESS");
};
},
error : function() {
alert("异常!");
}
});
}
</script>
</head>
<body>
<div id="form-div">
<form id="form1" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p>
<p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p>
<p><input type="button" value="登录" onclick="login()"> <input type="reset" value="重置"></p>
</form>
</div>
</body>
</html>
|