zoukankan      html  css  js  c++  java
  • @RequestBody接收ajax的json字符串

    在使用ajax进行请求,并传递参数时,偶尔需要把数组作为传递参数,这是就要使用@RequestBody来解决这个问题

    在页面端的处理:

    (1)利用JSON.stringify(arr)需要把json对象数组转变成一个json对象字符串
    (2)在ajax的参数中设置"contentType": "application/json"

      $(function(){
             $("#exe").on("click",function(){
                var arr = new Array();
                arr.push({"name":"lcs","age":18});
                arr.push({"name":"yds","age":19});
                arr.push({"name":"hrl","age":20});
                arr.push({"name":"lyf","age":21});
                var arrs = JSON.stringify(arr);
                $.ajax({
                    "url": "ajax_array.do",
                    "type": "post",
                    "data": arrs,
                    "contentType": "application/json",
                    "dataType": "json",
                    "success": function(result){
                        alert("请求成功!");
                    },
                    "error": function(){
                        alert("请求失败!");
                    }
                });
            }); 
        });

    在后端的处理:

    (1)利用RequestBody来接收JSON对象字符串,persons中是json对象数组进JSON.stringify(arr)转换的JSON对象字符串(数组的json对象字符串)

    (2)导入json-lib,利用其JSONArray和JSONObject的方法来解析获取JSON对象字符串中的数据

    (3)JSONArray.fromObject(persons)是把JSON对象字符串转换成JSON对象。

      @ResponseBody
        @RequestMapping("/ajax_array.do")
        //@RequestBody接收ajax请求的json字符串参数
        public String getPersons(@RequestBody Person[] persons){
            //将persons JSON字符串转换成JSON对象
            //JSONArray对象,有点像list对象
            JSONArray arrs = JSONArray.fromObject(persons);
            List<Person> personList = new ArrayList<Person>();
            //遍历JSONArray
            for(int i=0; i<arrs.size(); i++){
                Person person = new Person();
                //getJSONObject(i)是一个json对象
                String name = arrs.getJSONObject(i).getString("name");
                int age = arrs.getJSONObject(i).getInt("age");
                person.setName(name);
                person.setAge(age);
                personList.add(person);
            }
            System.out.println(personList);
            return "success";
        }
  • 相关阅读:
    JS获取四位年份和2位年份
    notebook 快捷键
    发表文章不需要版面费的期刊
    命题演算、集合论和布尔代数之间的关系是什么?
    炒作套路
    如何理解佛经中“黄叶止啼”的故事
    期货之为什么要注册仓单!逼空是什么鬼!
    反证法与归谬法的区别
    感恩的含义!告诉你什么是感?什么是恩?人生必读!
    悖论的本质
  • 原文地址:https://www.cnblogs.com/gangbalei/p/6185340.html
Copyright © 2011-2022 走看看