controller的返回数据需要为json时,没有配置正确。
解决:
controller返回json格式给ajax请求的两种方法
- JSON.toJsonString();
@RequestMapping(value = "allBookName", produces = "text/html;charset=UTF-8")
public @ResponseBody String allBookName() {
List<String> allBookName = bs.getBookName();
List<QueryBoxData> allBookNameData = new ArrayList<QueryBoxData>();
for (int i = 0; i < allBookName.size(); i++) {
allBookNameData.add(new QueryBoxData(i, allBookName.get(i), false));
}
return JSON.toJSONString(allBookNameData);
}
返回类型为String。
produces = “text/html;charset=UTF-8”
用的json工具是fastjson,pom.xml文件导入依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.53</version>
</dependency>
- 返回对象或集合
@ResponseBody
@SystemControllerLog(type=2,description="添加一个员工")
@RequestMapping(value = "add", produces = "application/json;charset=utf-8")
public JsonData addEmp(@RequestParam("empName") String empName,
@RequestParam("empDept") String empDept,
@RequestParam("empHireDate") String empHireDate,
@RequestParam("empStatus") String empStatus,
@RequestParam("jobName") String jobName,
@RequestParam("bankAccount") String bankAccount) {
JsonData data = new JsonData("addEmp",
es.addEmp(empName, empDept, empHireDate, empStatus, jobName, bankAccount), "添加员工", true);
return data;
}
produces=“application/json;charset=utf-8”
这里用的json工具是jackson。pom.xml引入依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>