1.要实现ssm下Ajax和后台j之间通过json进行交互,首先要ssm支持以json的数据方式发响应前台
2.jar包的支持(使用了jackson实现对象和JSON之间的转换)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.9.5</version>
</dependency>
3.jQuery的AJAX请求(详细参数见API)
<script>
$(function () {
$("#btn1").click(function () {
/* alert("ok")*/
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/ajax",
data: "name=hdh&age=12",
dataType: "json",
success: function (data) {
alert("name:" + data.name + " " + "age:" + data.age);
}
})
})
})
</script>
4.后台需要接收ajax的参数并相应一个json对象给前台
@RequestMapping("/json")
@ResponseBody
public User json(HttpServletResponse response) throws IOException {
/*response.getWriter().write("123");*/
return new User("hdh", 12);
}
5.AJAX携带参数的3中方式
ajax带参数提交的方式
1.直接拼接的方式 data: "name=hdh&age=12",
2.提交一个对象的方式 data: "name=hdh&age=12",
3.使用jquery的serialize()方法提交表单的数据 data: $("form").serialize(),
serialize():将表单中的数据序列化
var user={
username:"hdh",
age:123
}
<form action="#" method="get" id="form">
<input type="text" name="name">
<input type="text" name="age">
</form>
<input type="button" value="发送ajax" id="btn1">
6.前台将对象转换为json传递给后台,后台接收json格式的对象
("#btn2").click(function () {
//js中的json
var user = {
name: 'hdh',
age: '12'
}
//object类型对象转化为json字符串
alert(JSON.stringify(user))
$.ajax({
type:"post",
url:"${pageContext.request.contextPath}/ajax3",
data:JSON.stringify(user),
contextType:"application/json",
success:function (data) {
alert("name:" + data.name + " " + "age:" + data.age);
}
})
})
使用@request注解接受JSON格式的对象
@RequestMapping("/ajax3")
@ResponseBody
public User json3(@RequestBody User user) throws IOException {
System.out.println(user);
return user;
}
浙公网安备 33010602011771号