JSON AJAX提交表单数据
程序员文章站
2022-07-12 18:09:26
...
前端页面
<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册</title>
</head>
<body>
<script>
function test(){
var formObject = {};
var form = $("#myForm").serializeArray();
$.each(form,function(i,item){
formObject[item.name] = item.value;
});
var data=JSON.stringify(formObject);
alert(data);
$.ajax({
url:'${pageContext.request.contextPath}/registerUser.action',
type:'post',
// data表示发送的数据
data:data,
// 定义发送请求的数据格式为JSON字符串
contentType : "application/json;charset=UTF-8",
//定义回调响应的数据格式为JSON字符串,该属性可以省略
dataType : "json",
//成功响应的结果
success : function(data){
if(data != null){
alert("用户信息"+data.id+"用户名"+data.name+data.age);
}
}
})
}
</script>
<%--<form action="${pageContext.request.contextPath}/registerUser.action" id="form1" method="post">--%>
<form id="myForm">
用户名:<input type="text" name="id" /><br />
密 码:<input type="text" name="name" /><br />
<input type="button" value="注册" id="formDemo" onclick="test()"/>
</form>
</body>
</html>
后台接收收据
// 表单运用json进行前后台传递数据
@RequestMapping(value="/registerUser.action",method = RequestMethod.POST)
@ResponseBody
public User registerUser(@RequestBody User user)
{
User user1 = userMapper.selectByPrimaryKey(user.getId());
if(user1==null)
{
userMapper.insert(user);
user1 = userMapper.selectByPrimaryKey(user.getId());
String s = user1.toString();
return user1;
}else {
return null;
}
}
上一篇: ajax提交表单数据不跳转
下一篇: Ajax提交表单数据应注意