【问题标题】:RequestBody is null in controllerRequestBody 在控制器中为空
【发布时间】:2018-10-30 13:21:36
【问题描述】:

我正在尝试通过 jQuery AJAX 将 JSON 对象从前端发送到后端。 使用 POST 方法在请求的路径“/survey”上成功执行 ajax 调用。 问题是,我的@RequestBody final HmmSurveyForm hmmSurveyForm 的字段“answer1”和“heading”为空值。 当我在谷歌浏览器中检查请求时,开发者请求已发送:

但是对于来自前端的填充字段的响应为空:

我在前端有以下代码:

postSurvey: function() {
        $.ajax({
            url: this.encodedContextPath + "/survey",
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: ACC.hmmSurvey.getJSONDataForSurvey(),
            async: true,
            success: function (response) {
                console.log(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("The following error occurred: " + textStatus, errorThrown);
            }
        });
}

getJSONDataForSurvey: function () {
        var json = [];

        json.push({"answer1": "1"});
        json.push({"heading": "Test"});

        return JSON.stringify({"hmmSurveyForm": json});
}

在后台:

@RequestMapping(value = "/survey", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody HmmSurveyForm postSurvey(@RequestBody final HmmSurveyForm hmmSurveyForm, final Model model) {
    System.out.println(hmmSurveyForm);
    return hmmSurveyForm;
}

public class HmmSurveyForm {

    private String heading;
    private String answer1;

    // getter, setters
}

【问题讨论】:

    标签: javascript java jquery ajax spring-mvc


    【解决方案1】:

    您在 JS 中错误地声明了您的 RQ 正文

    var json = [];
    json.push({"answer1": "1"});
    json.push({"heading": "Test"});
    console.log({"hmmSurveyForm": json});

    它的根 hmmSurveyForm 是一个不同对象的数组,与您的后端期望的内容无关。

    你应该使用下面的代码;

    var json = {};
    json["answer1"] = "1";
    json["heading"] = "Test";
    console.log({"hmmSurveyForm": json});

    查看更多关于 JS 中的 JSON 对象here

    【讨论】:

    • @Kapparino 你确实通过了JSON.stringify'd 版本的json 对吗?
    • 没错。我错过了 JSON.stringify getJSONDataForSurvey: function () { var json = {}; json["answer1"] = "1"; json["heading"] = "Test"; return JSON.stringify(json); }, 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    相关资源
    最近更新 更多