【发布时间】:2021-03-20 00:39:44
【问题描述】:
我正在尝试将一些 jsonArray 值添加到我的 ajax 响应正文中。但它一直给出错误500。我可以看到调用在控制器上并且还打印了值。但由于某种原因,它不会进入 ajax 响应体。如果我要返回课程,那么我可以看到 ajax 调用工作正常,但是当我试图将这些值传递给 jsonArray 时。我正在使用 Spring Boot。 我遇到了这种类型的错误。
GET http://localhost:5000/report/id?=2 500
ajax 调用:
$.ajax({
type: "GET",
url: "/report",
data: {
id: id
},
success: function (response) {
console.log(response)
},
});
控制器:
@RestController
@Autowired
ReportDAO reportDao;
@GetMapping(value = "/report")
public @ResponseBody JSONArray getReport(@RequestParam(value="id") Integer id) {
JsonArray report = new JSONArray();
try {
report = JSONArray.fromObject(reportDao.getReportById(id));
} catch(Ex e){
}
System.out.println(report); // this is returing the value but not in the main ajax resposne call
return report;
}
我得到一个我的控制器的数据是这种格式:
[{
"dataUrl: "va",
"id": 1,
"status": "active",
"dataJson": "[{
"id": 1,
"name": "Jon"
}]
}]
【问题讨论】:
-
您的错误实际上很可能是由于 Spring 在内部尝试使用 Jackson(JSON 库)将 JSONArray 中的字段转换为 JSON 对象。 ...因此,无论
reportDao.getReportById(id)的返回类型是什么,都在此控制器方法上设置返回类型,Spring 应该自动为您将其转换为 JSON -
另一种选择(不太理想),您可以返回类型
String而不是JSONArray并返回report.toString()
标签: java json ajax spring spring-boot