&引用;JSON输入意外结束“;基于mvc的Ajax控制器
我有一个SpringMVC/Thymeleaf应用程序,如果我返回一个&引用;JSON输入意外结束“;基于mvc的Ajax控制器,ajax,spring,spring-boot,spring-mvc,Ajax,Spring,Spring Boot,Spring Mvc,我有一个SpringMVC/Thymeleaf应用程序,如果我返回一个布尔值,下面的Ajax处理工作得非常好。但是,只要方法是void,我就会得到错误 Firebug中JSON输入的意外结束。这是一个POST请求 @ResponseBody @PostMapping("/addOrUpdate") public void /*boolean works!*/ addOrUpdate(@RequestBody String json) throws Exception { service.
布尔值
,下面的Ajax处理工作得非常好。但是,只要方法是void
,我就会得到错误
Firebug中JSON输入的意外结束。这是一个POST请求
@ResponseBody
@PostMapping("/addOrUpdate")
public void /*boolean works!*/ addOrUpdate(@RequestBody String json) throws Exception {
service.addOrUpdateUserRoles(json);
/*boolean works - return true;*/
}
JS
如果我只是从方法定义中删除@ResponseBody
,Thymeleaf会抱怨,
org.thymeleaf.exceptions.TemplateInputException:解析模板[addOrUpdate]时出错,模板可能不存在或任何已配置的模板解析程序都无法访问该模板
我遵循了ResponseEntity
示例,但没有帮助——同样的错误,JS进入错误部分,输入意外结束
@ResponseBody
@PostMapping("/addOrUpdate")
public ResponseEntity addOrUpdate(@RequestBody String json) throws Exception {
service.addOrUpdate(json);
return new ResponseEntity(HttpStatus.OK);
}
使用
dataType:'json'
,您告诉jQuery您希望json作为响应。空响应不是有效的JSON,错误消息JSON输入的意外结束
正告诉您这一点
如果您不想从
addOrUpdate
控制器方法返回任何内容,请删除@ResponseBody
注释,因为没有响应正文,并坚持使用ResponseEntity
,但使用HttpStatus.no\u CONTENT
通知响应中的客户端没有预期内容。另外,将您的数据类型
更改为可能为空的数据类型,如'text'
如异常所述,故障点是输入的。您需要发送
json
格式输入
$.ajax({
type : "post",
dataType : 'json',
contentType : 'text/plain',
url : 'addOrUpdate',
data : {id: id}
...
基于 控制器
@PostMapping("/addOrUpdate")
public ResponseEntity<String> addOrUpdate(@RequestBody String json) throws Exception {
try {
service.addOrUpdate(json);
return new ResponseEntity<String>(HttpStatus.OK); // No exceptions
}
catch (Exception e) {
log.error("Error", e);
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); // This will enable JS to catch the Exception from Ajax
}
}
我按照你说的做了所有的事情,但是返回了HttpStatus.OK,因为这似乎更具信息性,而且它正在工作。非常感谢@geneb.“无内容”也是一种“成功”的响应状态——事实上,它的信息量更大,因为它传达了不需要任何内容的附加信息。看见
@PostMapping("/addOrUpdate")
public ResponseEntity<String> addOrUpdate(@RequestBody String json) throws Exception {
try {
service.addOrUpdate(json);
return new ResponseEntity<String>(HttpStatus.OK); // No exceptions
}
catch (Exception e) {
log.error("Error", e);
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); // This will enable JS to catch the Exception from Ajax
}
}
$.ajax({
type : "post",
dataType : 'text', // Returns a ResponseEntity, not JSON (Void method)
contentType : 'text/plain',
url : 'addOrUpdate',
data : somedata
})
.then(function() {
//...
})
.fail(function(jqXHR, textStatus, errorThrown) {
//... - will come here for a ResponseEntity of 'Bad Request'
});