嗨,我需要使用 AJAX 将完整模型和一个字符串从 html 传递到 Spring Controller 。我使用下面的代码片段,但它不起作用。
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
问题是,如果我单独传递模型(str)或单独传递字符串(tempCnltName),我可以在 Controller 中获取它,但无法将两者放在一起。
我的 Controller 如下:
@RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public @ResponseBody AjaxResponse checkDuplicateConsultantOnline(
@ModelAttribute("consultantBidModel") ConsultantBidModel model,
@RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
最佳答案
在服务器端,您已准备好接收模型(使用 @ModelAttribute
)和附加 URL 参数(使用 @RequestParam
)
在客户端上,将 URL 参数附加到 URL。假设 str
是您的模型,tempCnltName
是要提交到服务器的字符串:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
关于java - 使用 ajax 将模型和字符串传递给 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488407/