標籤:map return 2.4 pre post span name 建立 範圍
1 springmvc和ajax的互動1.1 請求字串響應json
用戶端發送的資料:key=value&key1=value1
響應回來:json
1.1.1json的支援jar包
1.1.2建立Handler處理器
1 package org.guangsoft.controller; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.guangsoft.pojo.User; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.web.bind.annotation.RequestBody; 9 import org.springframework.web.bind.annotation.RequestMapping;10 import org.springframework.web.bind.annotation.ResponseBody;11 12 @Controller13 public class UserHandler14 {15 //responseBody將傳回值轉化為json格式響應到用戶端16 //requestBody將請求資料轉化為json對象17 @RequestMapping("/checkUsername")18 public @ResponseBody List<User> CheckUsername(User user)19 {20 System.out.println(user.getUsername());21 List<User> userList = new ArrayList<User>();22 User user0 = new User();23 user0.setUsername("java");24 User user1 = new User();25 user1.setUsername("javase");26 User user2 = new User();27 user2.setUsername("javaee");28 //對象加入集合29 userList.add(user0);30 userList.add(user1);31 userList.add(user2);32 return userList;33 }34 35 @RequestMapping("/checkUsername2")36 public @ResponseBody List<User> CheckUsername2(@RequestBody User user)37 {38 System.out.println(user.getUsername());39 List<User> userList = new ArrayList<User>();40 User user0 = new User();41 user0.setUsername("java");42 User user1 = new User();43 user1.setUsername("javase");44 User user2 = new User();45 user2.setUsername("javaee");46 //對象加入集合47 userList.add(user0);48 userList.add(user1);49 userList.add(user2);50 return userList;51 }52 }
1.1.3完成ajax發送請求
備忘:springmvc ajax,響應json406錯誤,使用json相關jar包2.4以上版本。
1 function sendAjax() 2 { 3 var username = $("#username").val(); 4 var age = $("#age").val(); 5 var div = $("#showDiv"); 6 $.ajax( 7 { 8 url:"checkUsername.action", 9 data:{"username":username,"age":age},10 type:"post",11 dataType:"json",12 success:function(data)13 {14 var jsons = data;15 div.html("");16 for(var i = 0; i < jsons.length; i++)17 {18 div.append("<div>"+jsons[i].username+"</div>");19 } 20 }21 });22 }
1.2請求json響應json
用戶端發送的資料:{key:value,key1:value1}
響應回來:json
1.2.1 建立伺服器端Handler
見上
1.2.2用戶端發生ajax請求
1 function sendAjax2() 2 { 3 var username = $("#username").val(); 4 var age = $("#age").val(); 5 var div = $("#showDiv"); 6 $.ajax( 7 { 8 url:"checkUsername2.action", 9 type:"post",10 data:‘{"username":"username","age":"4"}‘,11 contentType:"application/json;charset=utf-8",12 dataType:"json",13 success:function(data)14 {15 var jsons = data;16 div.html("");17 for(var i = 0; i < jsons.length; i++)18 {19 div.append("<div>"+jsons[i].username+"</div>");20 }21 }22 });23 }
2url跳轉
Model封裝資料的範圍request範圍,只有請求轉寄才能擷取
如果是重新導向變為url傳參。
Return “forward:url”:請求轉寄
Return “redirect:url”重新導向
SpringMVC與Ajax互動