function requestJson(){ $.ajax.({ type : “post”, url : “${pageContext.request.contextPath}/testJson/responseJson”, contextType : “application/x-www-form-urlencoded;charset=utf-8”,//默认值 data : ‘{“username” : “name “, “gender” : “male”}’, dataType : “json”, success:function(data){ console.log(“服务器处理过的用户名是:” + data.username); console.log(“服务器处理过的性别是:” + data.gender); } }); }
function requestJson(){ var json = {“username” : “name “, “gender” : “male”}; var jsonstr = JSON.stringify(json);//json对象转换json字符串 $.ajax.({ type : “post”, url : “${pageContext.request.contextPath}/testJson/responseJson”, contextType : “application/json;charset=utf-8’ traditional:true,//这使json格式的字符不会被转码, data : jsonstr, dataType : “json”, success:function(data){ console.log(“服务器处理过的用户名是:” + data.username); console.log(“服务器处理过的性别是:” + data.gender); } }); }
下面介绍以上参数的含义:
type:Http请求的方式,通常使用POST和GET
url:请求的url地址,也就是咱们所要请求的Controller的地址
contextType:这里要注意,若是使用的是key/value值,那么这个请求的类型应该是application/x-www-form-urlencoded/charset=utf-8,该值也是默认值。
若是是JSON格式的话应该是application/json;charset=utf-8
traditional:若一个key是个数组,即有多个参数的话,能够把该属性设置为true,这样就能够在后台能够获取到这多个参数。
data:要发送的JSON字符串
success:请求成功以后的回调函数
error:请求失败以后的回调函数javascript
SpringMVC须要的jar包:jackson-core-asl-x.x.xx.jar、jackson-mapper-asl-x.x.xx.jar
SpringMVC配置文件中添加:java
@RequestMapping("/requestJson") public @ResponseBody Person requestJson(Person p) { System.out.println("json传来的串是:" + p.getGender() + " " + p.getUserName() + " " +p.isAdalt()); p.setUserName(p.getUserName().toUpperCase()); return p; } Person的实体类: public class Person { private String userName; private String gender; private boolean adalt; }
@RequestBody(接收的是JSON的字符串而非JSON对象),注解将JSON字符串转成JavaBean @ResponseBody注解,将JavaBean转为JSON字符串,返回到客户端。具体用于将Controller类中方法返回的对象,经过HttpMessageConverter接口转换为指定格式的数据,好比JSON和XML等,经过Response响应给客户端。produces=”text/plain;charset=utf-8”设置返回值。 ②把JSON字符串发送过来,使用注解@RequestBody接收String字符串以后,再解析出来 @RequestMapping(value = "testAjax.action",method = RequestMethod.POST) public void testAjax(@RequestBody String jsonstr){ JSONObject jsonObject = JSONObject.parseObject(jsonstr);//将json字符串转换成json对象 String age = (String) jsonObject.get("age");//获取属性 System.out.println(age); } ③固然也能够使用Map集合 @RequestMapping("/jsontest") public void test(@RequestBody Map map){ String username = map.get("username").toString(); String password = map.get("password").toString(); }