JSON(四)——異步請求中前后端使用Json格式的數據進行交互


json格式的數據廣泛應用於異步請求中前后端的數據交互,本文主要介紹幾種使用場景和使用方法。

一,json格式字符串

<input type="button" id="testBtn" value="測試按鈕" onclick="sentAjax();"/><br>
<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>

 

 

 

最后說一點,我們作為程序員,研究問題還是要仔細深入一點的。當你對原理了解的有夠透徹,開發起來也就得心應手了,很多開發中的問題和疑惑也就迎刃而解了,而且在面對其他問題的時候也可做到觸類旁通。當然在開發中沒有太多的時間讓你去研究原理,開發中要以實現功能為前提,可等項目上線的后,你有大把的時間或者空余的時間,你大可去刨根問底,深入的去研究一項技術,為覺得這對一名程序員的成長是很重要的事情。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM