jquery post json

来源:互联网 发布:王侯将相宁有种乎 编辑:程序博客网 时间:2024/05/19 06:36

jquery ajax调用,有的情况下提交的参数比较多,这时我们希望将这些参数作为一个json对象传递到controller中进行处理,那么就需要使用到post json对象的功能,下面的例子简单说明这个功能的使用。

  1. js代码,需要注意contentType:”application/json”,不然会出现415的错误
    <script type="text/javascript">    $(function(){        var para = {               name : 'lpn',              cname : 'shine'        };        var jsonpara = $.toJSON(para);        $("#checkName").click(function(){            $.ajax({                url : webContextPath + "/main/checkName",                async : true,                type : "POST",                contentType : "application/json",                dataType : "json",                data : jsonpara,                success : function(response) {                    var errorInfo = response.errorInfo;                    if (errorInfo != null) {                        $("#checkInfo").html(errorInfo);                    } else {                        $("#checkInfo").html("name is available");                    }                },                error : function() {                    alert("server exception");                }            });        });    });    </script>
  1. controller代码,需要注意@RequestBody的使用,它和@ResponseBody的作用一样,都是数据json处理
    @ResponseBody    @RequestMapping(value = "/checkName", method = RequestMethod.POST)    public Map<String, Object> checkName(@RequestBody CheckNameParam checkNameParam) {        System.out.println(checkNameParam.toString());        Map<String, Object> jsonMap = new HashMap<String, Object>();        return jsonMap;    }
0 0