SpringMvc jQueryAjax
jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Demo</title>
<style>
body, input, select, button, h1 {
font-size: 28px;
line-height:1.7;
}
</style>
</head>
<body>
<h1>员工查询</h1>
<label>请输入员工编号:</label>
<input type="text" id="keyword" />
<button id="search">查询</button>
<p id="searchResult"></p>
<h1>员工新建</h1>
<label>请输入员工姓名:</label>
<input type="text" id="staffName" /><br>
<label>请输入员工编号:</label>
<input type="text" id="staffNumber" /><br>
<label>请选择员工性别:</label>
<select id="staffSex">
<option>女</option>
<option>男</option>
</select><br>
<label>请输入员工职位:</label>
<input type="text" id="staffJob" /><br>
<button id="save">保存</button>
<p id="createResult"></p>
<script src="<%=basePath%>resources/js/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
$("#search").click(function(){
$.ajax({
type: "GET",
url: "<%=basePath%>jac/search?number=" + $("#keyword").val(),
dataType: "json",
success: function(data) {
if (data.success) {
$("#searchResult").html(data.msg);
} else {
$("#searchResult").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
});
$("#save").click(function(){
var name=$("#staffName").val();
var number= $("#staffNumber").val();
var sex=$("#staffSex").val();
var job=$("#staffJob").val();
var staff={"name":name,"number":number,"sex":sex,"job":job};
$.ajax({
type: "POST",
url: "<%=basePath%>jac/save",
data: staff,
dataType: "json",
success: function(data){
if (data.success) {
$("#createResult").html(data.msg);
} else {
$("#createResult").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
});
});
</script>
</body>
</html>
controller
@RequestMapping(value="/save",produces = {"text/javascript;charset=UTF-8"},method=RequestMethod.POST)
public @ResponseBody String save( Staff staff) throws JSONException{
......
return jsonObject;
}

浙公网安备 33010602011771号