<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>
<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>
@RequestMapping("/json") @ResponseBody public User json(HttpServletResponse response) throws IOException { /*response.getWriter().write("123");*/ return new User("hdh", 12); }
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">
("#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格式的對象jquery
@RequestMapping("/ajax3") @ResponseBody public User json3(@RequestBody User user) throws IOException { System.out.println(user); return user; }