步骤一:创建页面(student_add.html)
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 导入jquery -->
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
</head>
<body>
<form>
编号:<input type="text" id="id"/> <br/>
姓名:<input type="text" id="name"/> <br/>
年龄<input type="text" id="age"/> <br/>
性别:<input type="text" id="sex"/> <br/>
<input type="button" value="添加学生"/> <br/>
</form>
</body>
</html>
-
步骤二:给添加按钮绑定点击事件
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 导入jquery -->
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script>
// 页面加载成功
$(function() {
// 给按钮绑定事件
$("#bid").click(function(){
// 添加功能
});
})
</script>
</head>
<body>
<form>
编号:<input type="text" id="id"/> <br/>
姓名:<input type="text" id="name"/> <br/>
年龄<input type="text" id="age"/> <br/>
性别:<input type="text" id="sex"/> <br/>
<input type="button" id="bid" value="添加学生"/> <br/>
</form>
</body>
</html>
步骤三:提交操作(获得用户输入的数据、发送ajax进行提交、成功跳转到列表页面、失败提示)
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 导入jquery -->
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script>
// 页面加载成功
$(function() {
// 1.1 给按钮绑定事件
$("#bid").click(function(){
// 1.2 添加功能
// 1) 获得用户输入的数据
var student = {
"id" : $("#id").val(),
"name" : $("#name").val(),
"age" : $("#age").val(),
"sex" : $("#sex").val()
}
// console.info(student)
// 2) 发送ajax进行提交
$.ajax({
"url":"http://data.javaliang.com/data/jack/student",
"type":"post",
"contentType":"application/json;charset=UTF-8",
"data": JSON.stringify(student),
"dataType":"json",
"success":function(data){
// 判断
if(data.code == 1){
// 成功
alert(data.message)
// 跳转到列表页面
location.href = "student_list.html"
} else {
// 失败
alert(data.message)
}
},
"error":function(){
// 失败
alert("操作失败")
}
})
});
})
</script>
</head>
<body>
<form>
编号:<input type="text" id="id"/> <br/>
姓名:<input type="text" id="name"/> <br/>
年龄<input type="text" id="age"/> <br/>
性别:<input type="text" id="sex"/> <br/>
<input type="button" id="bid" value="添加学生"/> <br/>
</form>
</body>
</html>