通过Ajax进行POST提交JSON类型的数据到SpringMVC Controller的方法

十年热恋 提交于 2020-01-06 01:07:31

现在在做的项目用到了SpringMVC框架,需要从前端angular接收请求的JSON数据,为了测试方便,所以直接先用AJAX进行测试,不过刚开始用平时用的ajax方法,提交请求会出现415或者400错误,经过研究,终于可以了,现在做个总结。

js代码:

function postSimpleData() {        $.ajax({            type: "POST",            url: "Service/SimpleData",            contentType: "application/json", //必须有            dataType: "json", //表示返回值类型,不必须            data: JSON.stringify({ 'foo': 'foovalue', 'bar': 'barvalue' }),  //相当于 //data: "{'str1':'foovalue', 'str2':'barvalue'}",            success: function (jsonResult) {                alert(jsonResult);            }        });    }    function login(){    $.ajax({        url: "Service/login",       type: "POST",       contentType: "application/json",        dataType: "json",       data: JSON.stringify({            MachineIP:"127.0.0.1",          AppTag:"4",         RequestInfo:{                StaffCode:"",               Password:"",                StaffCard:"01411"           },      }),     async: true,       success: function(data) {          var ss = JSON.stringify(data);         $("#result").val(ss);          console.log(ss);     }   });    }    function postEmployees() {        $.ajax({            type: "POST",            url: "Service/Employees",            contentType: "application/json",            dataType: "json",            data: JSON.stringify({                "Employees": [                                    { "firstName": "Bill", "lastName": "Gates" },                                    { "firstName": "George", "lastName": "Bush" },                                    { "firstName": "Thomas", "lastName": "Carter" }                                 ]             }),            success: function (jsonResult) {                alert(jsonResult);            }        });    }

JAVA Controller代码:

@RequestMapping(value = "/SimpleData", method = RequestMethod.POST)    @ResponseBody    public ActionResult SimpleData(string foo, string bar) {        return Json("SimpleData", JsonRequestBehavior.AllowGet);    }     @RequestMapping(value = "/login", method = RequestMethod.POST)    @ResponseBody    public ResponseProtocolMap login(@RequestBody JSONObject requestJson, HttpServletRequest request) {        ResponseProtocolMap responseProtocolMap = null;        String machineIP = RequestJsonUtils.getMachineIP(requestJson);        String appTag = RequestJsonUtils.getAppTag(requestJson);        JSONObject requestInfo = RequestJsonUtils.getRequestInfo(requestJson);        if (requestInfo == null) {            responseProtocolMap = new ResponseProtocolMap("-1", "参数错误");        } else {            String staffCode = RequestJsonUtils.getValueByKey(requestInfo, "StaffCode");            String password = RequestJsonUtils.getValueByKey(requestInfo, "Password");            String staffCard = RequestJsonUtils.getValueByKey(requestInfo, "StaffCard");            responseProtocolMap = sysLoginService.login(staffCode, password, staffCard, appTag, request);        }        return responseProtocolMap;    }     @RequestMapping(value = "/Employees", method = RequestMethod.POST)    @ResponseBody    public ActionResult Employees(List<Employee> Employees) {        return Json("Employees", JsonRequestBehavior.AllowGet);    }

public class Employee{    public string FirstName { get; set; }    public string LastName { get; set; }}

值得注意的有2点:

1)Ajax 选项中

contentType: "application/json"

 这一条必须写,表明request的数据类型是json。

dataType: "json"

这一条表示返回值的类型,不是必须的,且依据返回值类型而定。

2)选项中

data: JSON.stringify({ 'foo': 'foovalue', 'bar': 'barvalue' })

 很多时候我们将数据写作:

{ 'foo': 'foovalue', 'bar': 'barvalue' }

这样会导致错误,因为js会默认将这个json对象放到表单数据中,故而导致controller接收不到。

有两种办法处理:第一种方式是用JSON.stringify()函数,其中JSON被Ecmascript5定义为全局对象。

第二种方式是直接用双引号包裹起来,比如data: "{'str1':'foovalue', 'str2':'barvalue'}"。


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!