您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要讲解了Springmvc和ajax实现前后端交互的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
springmvc使用@RequestBody来获取前端的json字符串并转化为java对象
使用@ReponseBody来将返回的java对象转换为json形式返回前端
下面是几个使用springmvc和ajax进行前后端交互的简单实例
1.传递简单对象:
前端:
$(function(){ $("#btn3").click(function(){ //准备好要发的数组 var array=[16,18,56]; var jsonArray=JSON.stringify(array); $.ajax({ "url":"send/three/array.html", "type":"post", "data":jsonArray, "dataType":"text", "contentType":"application/json;charset=UTF-8", "success":function (response) { alert(response); }, "error":function (response) { alert(response); } } ); }); });
后端:
@ResponseBody @RequestMapping("/send/three/array.html") public String testReceiveArrayThreee(@RequestBody List<Integer> array){ for (int i : array) { System.out.println(i); } return "success"; }
结果:
2.传递复杂对象:
1.实体类:
public class Student { private Integer stuId; private String studentName; private Address address; private List<Subject> subjectList; private Map<String,String> map; get和set方法省略 } public class Subject { private String subjectName; private Integer subjectScore;} public class Address { private String province; private String city; private String street;}
2.前端ajax:
$(function(){ $("#btn4").click(function(){ //准备要发送的数据 var student={ "stuId":5, "studentName":"tom", "address":{ "province":"海南省", "city":"海南市", "street":"不知道" }, "subjectList":[ { "subjectName":"test", "subjectScore":60 }, { "subjectName":"ssm", "subjectScore":70 } ], "map":{ "k1":"v2", "k2":"v3", "k3":"v4" } }; //json对象转化为json字符串 var requestBody=JSON.stringify(student); $.ajax({ "url":"send/compose/object.json", "type":"post", "data":requestBody, "contentType":"application/json;charset=UTF-8", "dataType":"json", "success":function (response) { console.log(response); }, "error":function (response) { console.log(response); } } ); }); });
后端:
@ResponseBody @RequestMapping("/send/compose/object.html") public String testComposeObject(@RequestBody Student student){ System.out.println(student.toString()); return "success"; }
结果:
看完上述内容,是不是对Springmvc和ajax实现前后端交互的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。