採用阿里fastJson 下面是pom.xml
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.9</version> </dependency>
Ajax返回字串
//js前台ajax 注意引入jquery檔案 如jquery.min.js等 function testAjax() { //文本的值 var uname = $("#username").val(); var pwd = $("#password").val(); //alert(pwd) $.ajax({ type : 'post', //提交方式 url : "../ReturnString.do", //路徑 //參數 data : { username : uname, password : pwd }, cache : false, //返回普通的字元流不要寫 dataType : "json" success : function(data) { alert(data); } }); } //html代碼 我綁定的是焦點失去事件 所以加了一個測試框 <form action="#" id="myform"> 姓名:<input type="text" id="username" name="username" /><br /> 密碼:<input type="text" name="password" id="password" onblur="testAjax()" /> <br /> 測試框:<input type="text" /> <br /> ${pageContext.request.contextPath} </form> //後台代碼 只是功能測試 沒有寫實際內容 @RequestMapping("/ReturnString") //這是spring架構的註解 public void ReturnString(String username,String password,HttpServletResponse response){ System.out.println(username+password); try { //寫入out物件流程 response.getWriter().println("測試的字串"); } catch (IOException e) { e.printStackTrace(); } }
Ajax返JSON格式
//前台ajaxfunction ReturnJsonList() { $.ajax({ type : 'post', url : '../ReturnJsonList.do', dataType : "json", success : function(data) { alert(data); //i迴圈的次數 value對象 id,name等是屬性 $.each(data, function(i, value) { $("#remark").append( " <tr><td>" + value.id + "</td><td>" + value.name + "</td><td>" + value.t + "</td><td>" + value.x + "</td></tr>"); }); } }); }
//html代碼 測試用的按鈕的單擊時間 然後返回集合拼接到表格 <input type="button" name="測試返回JSON格式List集合" onclick="ReturnJsonList()" /> <table class="table table-striped" id="remark"> <tr> <td>學號</td> <td>姓名</td> <td>日期</td> <td>年齡</td> </tr> </table>
//後台代碼@RequestMapping("/ReturnJsonList") public void testPrco(HttpServletResponse response){ System.out.println("ok ReturnJsonList"); try { List<Demo> list = new ArrayList<>(); Demo d1 = new Demo(1,"測試01", 50, new Date()); Demo d2 = new Demo(2,"測試02", 50, new Date()); Demo d3 = new Demo(3,"測試03", 50, new Date()); //日期轉換 在實體物件屬性上加@JSONField (format="yyyy-MM-dd") list.add(d1); list.add(d2); list.add(d3); /*Map<Integer, String> map = new HashMap<>(); map.put(1, "test01"); map.put(2, "test02"); map.put(3, "test03");*/ //簡單粗暴,對於Map這句也適用 String json = JSON.toJSONString(list); System.out.println(json); //取得流向JSP傳遞資料 response.getWriter().println(json); } catch (IOException e) { e.printStackTrace(); } }
附
Json格式轉換
public static void main(String[] args) { List<Object> list = new ArrayList<>(); list.add("測試"); list.add("測試2"); list.add("測試3"); //JSON格式轉換 map 字串都適應 String str = JSON.toJSONString(list); System.out.println(str); }
結果
["測試","測試2","測試3"]