前端jQuery传递JSON给SpringMVC接收并返回JSON

本文详细介绍了前后端通过JSON进行数据交换的过程,包括前端使用jQuery发起AJAX请求、JSON数据的序列化与发送,以及后端SpringMVC如何配置与接收JSON数据,最后解析并返回JSON响应。

萌新记录下自己踩过的坑 把我写的前后端传递JSON的流程写下来 

为了实现功能 也翻过许多文章 弄了一天才把这点东西打通 呜呜呜 我实在是太菜了

1.首先在ready函数里面用一个click触发ajax contentType写'application/json',dataType写'json',然后把JSON对象转换为json字符串  var myJSON = JSON.stringify(obj);用ajax传递myJSON就可以了。

$("#bit").click(function(){
        var zio2 = "zio2";
        var obj = {"build":"123","zio":"zio"};
        var myJSON = JSON.stringify(obj);
        console.log(myJSON);//必须传String类型的json
        $.ajax({
                type:"post",
                url:"testMVC",
                dataType:'json',
                contentType:'application/json',//必须传String类型的json 传到后端后变成JSON对象
                data:myJSON,
                success:(msg)=>{//后端传的是字符串,转化为json  前端接收到的是JSON的数据
                    console.log(msg.exaid);
                    $('#data').html(msg.exaid);
                },
                error:(xhr)=>{
                    alert(xhr.status);
                }
            });

}

 

2.然后下载这三个包jackson-databind-2.11.0.jar,jackson-core-2.11.0.jar,jackson-annotations-2.11.0.jar,fastjson-1.2.70.jar

 

3.springmvc.xml文件里面要有这个元素

<mvc:annotation-driven/>
<mvc:default-servlet-handler/>

 

4.SpringMVC里面用Map接收 也可以用其他的对象接收 不过我没用试过 

5.要传递JSON对象 先转换成 json字符串 用这个函数:JSON.toJSONString(map);然后 写入response.setContentType("application/json");

6.最后打印想要传递的 json字符串:response.getWriter().print(json);

 

@RequestMapping(value="/testMVC",method=RequestMethod.POST)
@ResponseBody
public void testMVC( @RequestBody(required=true) Map<String,Object> map ,HttpServletRequest request, HttpServletResponse response) {
            map.put("exaid","exaid");
            String json = JSON.toJSONString(map);
            System.out.println(json);
            System.out.println(String.class.isInstance(json));
            response.setContentType("application/json");
            try {
                response.getWriter().print(json);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

7.前端ajax的success函数直接接受

success:(msg)=>{//后端传的是json字符串,转化为json  前端接收到的是JSON的数据
                    console.log(msg.exaid);
                    $('#data').html(msg.exaid);
                },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值