javascript - AJAX 使用 POST 映射将所有空数据发送到 Spring 控制器?
问题描述
我正在尝试使用 ajax 将带有 POST 映射的 HTML 表单中的数据发送到 spring 控制器。但它正在发送所有空数据。为 ajax 尝试了很多变化。它正在发送学校对象,但所有字段均为空。控制台显示字段正在保存,但在 AJAX 中全部变为空。
这是 createSchoolForm.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title>Create School || EDUBD</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
</head>
<body>
<h1>EDUBD - Manage School Portal</h1>
<h3>Create New School</h3> <br>
<form id="createSchool">
<br>
<label>School Name:
<input type="text" id="schoolName" value="" />
</label>
<br>
<label>School Email:
<input type="text" id="schoolEmail" value="" />
</label>
<br>
<label>School Phone Number:
<input type="tel" id="schoolPhone" value="" />
</label>
<br>
<input id="btn" type="submit" value="Submit" />
</form>
<div id="feedback"></div>
<script>
$(document).ready( function() {
$("#createSchool").submit(function(e){
e.preventDefault();
var schoolData = {
schoolName: $("#schoolName").val(),
schoolEmail: $("#schoolEmail").val(),
schoolPhone: $("#schoolPhone").val(),
status: null,
schoolStreet: null,
schoolHouse: null,
schoolZip: null,
schoolCity: null,
schoolState: null,
schoolCountry: null,
image: null,
createBy: null,
updatedBy: null,
createdDate: null,
updatedDate: null,
id: null
};
// let j = JSON.stringify(schoolData);
console.log(JSON.stringify(schoolData));
$.ajax({
header:{
contentType : 'application/x-www-form-urlencoded; charset=UTF-8'
},
type : "post",
url : "Create",
data : JSON.stringify(schoolData),
dataType : "json",
success: function (data) {
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
console.log("SUCCESS : ", data);
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>"
+ e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
}
});
});
});
</script>
</body>
</html>
这是控制器:
@ApiOperation(value = "Create School")
//@PostMapping(BASE_SCHOOL_PATH+"/Create")
@PostMapping(value = BASE_SCHOOL_PATH+"/Create", produces = {"application/json"},
consumes = {"application/x-www-form-urlencoded"})
public String create (School school, @ApiIgnore HttpServletResponse response) throws IOException {
// components tests are expecting this assertion and exception handling, and will fail if removed
try {
Assert.isNull(school.getId(), "School ID field must be null");
Assert.notNull(school.getSchoolEmail(),"School email cannot be null.");
Assert.notNull(school.getSchoolPhone(),"School Phone number cannot be null. ");
Assert.isNull(schoolDao.readByEmail(school.getSchoolEmail()),"School already exists in the system.");
schoolDao.create(school, null);
return "createSchoolForm";
} catch (IllegalArgumentException e) {
logger.error(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
return null;
} catch (Exception e) {
logger.error(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
return null;
}
}
解决方案
在您的 ajax 函数中,尝试将数据作为表单数据发送:
首先,使用 HTML 表单创建一个表单数据对象:
let createSchoolForm = document.getElementById('createSchool');
let formData = new FormData(createSchoolForm );
然后,将其添加到data
Ajax 对象中的键中。删除header
anddataType
因为它可能与 Ajax 通信冲突。
$.ajax({
type : "post",
url : "Create",
data : formData
success: function (data) {
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
console.log("SUCCESS : ", data);
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>"
+ e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
}
});
完整示例:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title>Create School || EDUBD</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
</head>
<body>
<h1>EDUBD - Manage School Portal</h1>
<h3>Create New School</h3> <br>
<form id="createSchool">
<br>
<label>School Name:
<input type="text" id="schoolName" value="" />
</label>
<br>
<label>School Email:
<input type="text" id="schoolEmail" value="" />
</label>
<br>
<label>School Phone Number:
<input type="tel" id="schoolPhone" value="" />
</label>
<br>
<input id="btn" type="submit" value="Submit" />
</form>
<div id="feedback"></div>
<script>
$(document).ready( function() {
$("#createSchool").submit(function(e){
e.preventDefault();
var schoolData = {
schoolName: $("#schoolName").val(),
schoolEmail: $("#schoolEmail").val(),
schoolPhone: $("#schoolPhone").val(),
status: null,
schoolStreet: null,
schoolHouse: null,
schoolZip: null,
schoolCity: null,
schoolState: null,
schoolCountry: null,
image: null,
createBy: null,
updatedBy: null,
createdDate: null,
updatedDate: null,
id: null
};
// let j = JSON.stringify(schoolData);
console.log(JSON.stringify(schoolData));
let createSchoolForm = document.getElementById('createSchool');
let formData = new FormData(createSchoolForm );
$.ajax({
type : "post",
url : "Create",
data : formData
success: function (data) {
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
console.log("SUCCESS : ", data);
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>"
+ e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
}
});
});
});
</script>
</body>
</html>
推荐阅读
- active-directory - 有人在 3389 上使用 RDP 访问我们的服务器吗?
- python - Tensorflow Keras嵌入层错误:层权重形状不兼容
- rest - 在一个 RESTful API 请求中从两个不同的表中删除资源
- r - geom_bar 或 geom_col 中的多个变量
- junit - 模拟一个 void 方法
- firebase - 是否有用于管理 Firebase App Distribution 测试人员的 API?
- reactjs - 如何使用 React + TypeScript 通过遍历数组来渲染组件?
- wix - WiX 在主要升级期间保留注册表,但在卸载时删除
- c# - 为什么 Andrew 的单调算法需要 O(N LogN) 次?
- python-3.x - pyspark 将最小值添加回数据框