请求报错Required String parameter ‘id‘ is not present

一个小坑,前端ajax 请求后台一直报错Required String parameter 'id' is not present,查了半天资料才发现原因

前端开始用的POST方式,后端用@RequestParam接收id,一直接收不到,不得已换了@RequestBody,感觉实在难受,百度了一遍才明白

参考  https://blog.csdn.net/baicp3/article/details/49737795

         https://www.jianshu.com/p/b3596ffef3d7

 //发送ajax请求
            var url = "/content/selectByid.do";
            var idData = {"id" : data.id};
            $.ajax({
                url:url,
                type:"get",
                data:idData,
                dataType:"json",
                contentType: 'application/json;charset=UTF-8',
                success:function (rs) {
                console.log(rs)
            }
            })
 /*   按照id查询*/
    @RequestMapping("selectByid.do")
    @ResponseBody
    //public Content selectByid(@RequestBody Content content){
        public Content selectByid(@RequestParam("id") String id){
        Content content = contentService.selectByid(Integer.parseInt(id));
        //Integer id = content.getId();
       logger.info("id============>"+id);
        return content;
    }

前端用get方式提交简单的数据,后端直接用@RequestParam("id")就可以,对应的请求是这样的

Request URL:http://localhost:8080/content/selectByid.do?id=6

但如果前端使用POST,前端数据要JSON.stringifl,后端要用@RequestBody

//发送ajax请求
                var url = "/content/delByid.do";
                var params = {"id" : data.id};
                $.ajax({
                    url:url,
                    data:JSON.stringify(params),
                    type:"post",
                    success:function (resultData) {
                        //成功后的回调函数
                        console.log(resultData);
                            tableIns.reload();
                            layer.close(index);
                    },
                    dataType:"json",
                    contentType: 'application/json;charset=UTF-8'
                });

关于JSON.stringifl  参考  JSON.stringify()与JSON.parse()的区别

猜你喜欢

转载自blog.csdn.net/LvFengQi/article/details/114849309