javascript - RequestBody 在控制器中为空
问题描述
我正在尝试通过 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
}
解决方案
您在 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 对象的更多信息
推荐阅读
- elasticsearch - filebeat 未在 linux 中启动,并且没有打印日志以进行故障排除
- azure - Azure 用作作业调度程序应用程序
- flutter - 如何在容器父级中将具有行作为子级的列居中
- prolog - Prolog重复元素到多次
- python - 有没有办法在多维列表中找到最高值?
- node.js - NodeJS表单垃圾邮件预防
- sql - 在 SQL Inject 测试的查询号后添加“”的原理是什么?
- c# - 创建一个返回项目数组数组的过滤器
- mongodb - Mongo DB副本集如何为特定集合数据库配置复制
- python - Pandas.DataFrame.GroupBy.agg,聚合函数中需要的独立列。如何将其放入 agg 中?