JSON 格式的数据广泛应用于异步请求中前后端的数据交互, 本文主要介绍几种使用场景和使用方法.
- <input type="button" id="testBtn" value="测试按钮" onclick="sentAjax();"/><br> 3 <script type="text/javascript">
- function sentAjax(){
- $.Ajax({
- type: 'POST',
- url:"<%=basePath%>/manage/test/ajax",
- dataType : "json",
- success: function(result){
- // 这里 result 是一个符合 JSON 格式的 JS 对象
- //alert(result.name);
- //alert(result[0].name);
- //alert(result.listUser[0].name);
- }
- });
- }
- </script>
java 代码
- @RequestMapping(value = "/ajax")
- public void testAjax(HttpServletRequest request, HttpServletResponse response){
- try {
- String jsonStr1 = "{\"name\":\" 张三 \",\"age\":23}";
- String jsonStr2 = "[{\"name\":\" 张三 \",\"age\":1},{\"name\":\" 李四 \",\"age\":24}]";
- String jsonStr3 = "{\"listUser\": [{\"name\":\" 张三 \",\"age\":1},{\"name\":\" 李四 \",\"age\":24}] }";
- response.setCharacterEncoding("utf-8");// 响应字符集的编码格式
- response.getWriter().print(jsonStr3);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
另外使用 spring 的 @ResponseBody 这个注解的话还可以这样写
- @RequestMapping("/ajax")
- @ResponseBody
- public Object testAjax1(HttpServletRequest request, HttpServletResponse response){
- String jsonStr1 = "{\"name\":\" 张三 \",\"age\":23}";
- String jsonStr2 = "[{\"name\":\" 张三 \",\"age\":1},{\"name\":\" 李四 \",\"age\":24}]";
- String jsonStr3 = "{\"listUser\": [{\"name\":\" 张三 \",\"age\":1},{\"name\":\" 李四 \",\"age\":24}] }";
- return jsonStr1;
- }
二, java 对象
- @RequestMapping(value = "/ajax")
- public void testAjax2(HttpServletRequest request, HttpServletResponse response){
- try {
- User user = new User();
- user.setName("张三");
- user.setAge(23);
- JSONObject jsonObject = JSONObject.fromObject(user);
- response.setCharacterEncoding("utf-8");// 响应字符集的编码格式
- response.getWriter().print(jsonObject.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
使用以上的方式的话要先把 java 对象转换成 JSON 格式的字符串.
下面使用 springmvc 的 @ResponseBody 这个注解, 也是在 springmvc 的 web 项目开发中经常用到的.
- @RequestMapping(value = "/ajax")
- @ResponseBody
- public Object testAjax3(HttpServletRequest request, HttpServletResponse response){
- User user = new User();
- user.setName("张三");
- user.setAge(23);
- return user;
- }
在这里 @ResponseBody 这个注解对于 JSON 格式数据的解析用到了 jackson 这个框架另外它对响应对象 response 进行了封装, 这让我们在异步请求中使用 JSON 格式的数据进行数据交互更加的方便. 它的实现原理如下:
- @RequestMapping(value = "/ajax4")
- public void testAjax4(HttpServletRequest request, HttpServletResponse response){
- try {
- User user = new User();
- user.setName("张三");
- user.setAge(23);
- ObjectMapper mapper = new ObjectMapper();
- String userStr = mapper.writeValueAsString(user);
- response.setCharacterEncoding("utf-8");// 响应字符集的编码格式
- response.getWriter().print(userStr);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
另外在使用 JSON 格式数据交互时如有以下用法:
- @RequestMapping(value = "/ajax5")
- @ResponseBody
- public Object testAjax5(HttpServletRequest request, HttpServletResponse response){
- Map<String,Object> jsonMap = new HashMap();
- String jsonStr1 = "{\"name\":\" 张三 \",\"age\":23}";
- jsonMap.put("json", jsonStr1);
- return jsonMap;
- }
前端应该这么写
- <script type="text/javascript">
- function sentAjax(){
- $.Ajax({
- type: 'POST',
- url:"<%=basePath%>/manage/test/ajax5",
- dataType : "json",
- success: function(result){
- //result.JSON 取到的只是 map 在前端转换成 JSON 格式 JS 对象时 key 为'json'对应的字符串的值, 在前段 JSON 格式的字符串转换成 JSON 格式 JS 对象推荐使用 JSON.parse() 这个函数.
- var jsonStr = JSON.parse(result.JSON);
- alert(jsonStr.name)
- }
- });
- }
- </script>
来源: http://www.bubuko.com/infodetail-3041022.html