You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Thymeleaf向Spring Boot Controller提交AJAX POST时出现JSON解析错误

问题根源

你的AJAX请求设置了dataType: "json",明确要求后端返回JSON格式响应,但Spring Boot控制器返回的是视图名称(比如"supportrequest"),框架会自动渲染对应的HTML页面返回。前端拿到HTML内容后尝试按JSON解析,自然抛出语法错误。

两种解决方案

方案一:后端返回JSON,前端手动处理重定向

修改Spring Boot控制器,不再返回视图,而是返回JSON响应,由前端在成功回调里触发页面跳转:

@PostMapping("/updatesupportrequest")
public ResponseEntity<Object> createSupportRequest(@RequestParam(name = "bugid") int bugid, @RequestBody String requestBody) {
    System.out.println(bugid);
    DatabaseWriteResponse response = writeToDatabaseService
            .writeToDatabase(WriteToDatabaseService.PROCEDURE_UPDATESUPPORTREQUEST, requestBody);
    System.out.println(response.getResponse());
    
    if (response.getResponse().equals(DatabaseWriteResponse.SUCCESS)) {
        // 返回包含重定向地址的JSON对象
        return ResponseEntity.ok(Map.of("redirectUrl", "/supportrequest"));
    } else {
        // 错误时返回包含错误信息的JSON
        Map<String, String> errorData = new HashMap<>();
        errorData.put("response", response.getResponse());
        errorData.put("errorMsg", response.getMsg());
        return ResponseEntity.badRequest().body(errorData);
    }
}

修改AJAX的success回调,处理页面跳转:

var formData = JSON.stringify($('#supportrequest').serializeArray());

$.ajax({
    type: "POST",
    url: "/updatesupportrequest?bugid=" + $('#requestnum').val(),
    data: formData,
    success: function(res){
        console.log("success");
        // 跳转到指定页面
        window.location.href = res.redirectUrl;
    },
    error: function(xhr, status, error) {
        console.log(xhr);
        console.log(status);
        console.log(error);
        // 可选:显示后端返回的错误信息
        if(xhr.responseJSON){
            alert(xhr.responseJSON.errorMsg);
        }
    },
    complete: function(){
        console.log("complete");
    },
    dataType: "json",
    contentType : "application/json"
});

方案二:后端返回空响应触发AJAX success(不跳转)

如果不需要页面跳转,仅需触发AJAX的success函数,修改控制器返回空的成功响应即可:

@PostMapping("/updatesupportrequest")
public ResponseEntity<Void> createSupportRequest(@RequestParam(name = "bugid") int bugid, @RequestBody String requestBody) {
    System.out.println(bugid);
    DatabaseWriteResponse response = writeToDatabaseService
            .writeToDatabase(WriteToDatabaseService.PROCEDURE_UPDATESUPPORTREQUEST, requestBody);
    System.out.println(response.getResponse());
    
    if (response.getResponse().equals(DatabaseWriteResponse.SUCCESS)) {
        // 返回200状态码和空响应体,AJAX会识别为success
        return ResponseEntity.ok().build();
    } else {
        Map<String, String> errorData = new HashMap<>();
        errorData.put("response", response.getResponse());
        errorData.put("errorMsg", response.getMsg());
        return ResponseEntity.badRequest().body(errorData);
    }
}

此时前端AJAX的success会正常触发,无需额外修改代码。

补充:POST请求无法通过后端直接触发浏览器重定向,因为AJAX是异步请求,浏览器不会自动处理后端的302重定向响应,必须由前端通过window.location.href手动跳转。

内容的提问来源于stack exchange,提问作者rphello101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:40:19