我的javascript代码中的错误

Mat*_*ara 1 javascript java jquery spring spring-boot

当我向我的网址发送帖子请求时,我的控制器设法将记录保存到数据库,但我的ajax出错了.我究竟做错了什么?我的js代码:

function salvarValores(){
capturarValores()
$.ajax({
    type: "POST",
    url: "/service/newService/service",
    dataType: "json",
    contentType: 'application/json',
    data: JSON.stringify(( { 'cpfPessoa': cpfCliente, "descricaoServico": descricao } )),
    success: function(data){
        alert("Record successfully entered");
        location.reload();
    },
    error: function(data){
        alert("Error performing operation");
        location.reload();
    }
});
Run Code Online (Sandbox Code Playgroud)

}

我的春季启动控制器

@PostMapping("/service/newService/service")
@ResponseBody
public ResponseEntity<String> newService(@RequestBody  Service service) {

    if (serviceDao.addObject(service)) {
        logger.debug("Adding data");
        return new ResponseEntity<String>("Data successfully saved", HttpStatus.OK);
    }
    logger.error("Error to insert data in database");
    return new ResponseEntity<String>("Error to insert data in database", HttpStatus.FAILED_DEPENDENCY);
}
Run Code Online (Sandbox Code Playgroud)

当我单击保存按钮时,我有一条警告,其中显示"错误执行操作"但该记录已正确插入数据库

T.J*_*der 7

你已经告诉jQuery你期待JSON回来了:

$.ajax({
  // ...
  dataType: "json", // <== Here
  // ...
});
Run Code Online (Sandbox Code Playgroud)

...但你返回的不是JSON:

return new ResponseEntity<String>("Data successfully saved", HttpStatus.OK);
Run Code Online (Sandbox Code Playgroud)

因此,当jQuery尝试为您解析响应(作为JSON)时,它会失败.

删除dataType参数(或将其设置为"text").更多文档.