五、服务器端的 SpringMVC 如何返回 JSON 类型的字符串。
请求:
$("#testJson8").click(function () {
$.ajax({
url: "testReturnJsonValue",
type: "post",
success: function (result) {
console.log(result);
}
});
});
1.返回单个对象
handler 方法:
@ResponseBody
@RequestMapping("/testReturnJsonValue")public Person testReturnJsonValue() {
Person person = new Person();
person.setName("lily");
person.setAge(23); return person;
}
在浏览器控制台正常打印了 Person 对象。
注意:这里没有指定 dataType。
2.返回多个对象
handler 方法:
@ResponseBody
@RequestMapping("/testReturnJsonValue")public List testReturnJsonValue() {
List personList = new ArrayList<>();
Person person = new Person();
person.setName("lily");
person.setAge(23);
Person person2 = new Person();
person2.setName("lucy");
person2.setAge(33);
personList.add(person);
personList.add(person2); return personList;
}
在浏览器控制条正常打印了 Person 数组。
3.返回 Map
@ResponseBody
@RequestMapping("/testReturnJsonValue")public Map testReturnJsonValue() {
Map map = new HashMap<>();
Person person = new Person();
person.setName("lily");
person.setAge(23);
Person person2 = new Person();
person2.setName("lucy");
person2.setAge(33);
map.put("1", person);
map.put("2", person2); return map;
}
浏览器控制台输出:
4.在实际生产环境下的 Ajax 返回值。
封装一个返回值类型:
public class AjaxResult implements Serializable {
public static final String RESULT_CODE_0000 = "0000";
public static final String RESULT_CODE_0001 = "0001";
private String code;
private String message;
private Object data;
public AjaxResult() {
}
public String getCode() { return this.code;
}
public void setCode(String code) { this.code = code;
}
public String getMessage() { return this.message;
}
public void setMessage(String message) { this.message = message;
}
public Object getData() { return this.data;
}
public void setData(Object data) { this.data = data;
}
}
实际使用:
@ResponseBody
@RequestMapping("/testReturnJsonValue")
public AjaxResult testReturnJsonValue() {
AjaxResult ajaxResult = new AjaxResult();
try {
Map map = new HashMap<>();
Person person = new Person();
person.setName("lily");
person.setAge(23);
Person person2 = new Person();
person2.setName("lucy");
person2.setAge(33);
map.put("1", person);
map.put("2", person2);
ajaxResult.setData(map);
ajaxResult.setMessage("success!");
ajaxResult.setCode(AjaxResult.RESULT_CODE_0000);
} catch(Exception e) {
e.printStackTrace();
ajaxResult.setMessage("fail!");
ajaxResult.setCode(AjaxResult.RESULT_CODE_0001);
} return ajaxResult;
}
六、Request Payload
(1)出现的条件:
contentType: \'application/json;charset=utf-8\'
type:post
(2)具体请参看
(3)建议尽量不要手动的去处理此种情况,能选用别的方式避免就尽量避免。
七、总结
主要介绍了SpringMVC 对 Ajax 的支持,对与 Ajax 数据如何组织,重点介绍了对表单的支持。