我正在向后备弹簧控制器发出ajax调用。我看到由于发布而将数据成功保存到db中,但是在浏览器控制台上我看到POST抛出404。此外,一旦调用从spring控制器返回,就会调用ajax调用的错误功能。
有人可以告诉我我在这里想念的东西吗。
$('#submitMessage').submit(function(e){
e.preventDefault();
var formData = {};
var msg=document.getElementById('iconLeft4-1');
var url = "${context}/wasadmin/support/ajax/send";
formData['comment']=msg.value;
formData['commented_by']='1';
formData['supportId']='1';
formData['userType']='O';
console.log(JSON.stringify(formData));
$.ajax({
type : 'POST',
contentType: "application/json",
url : url,
dataType : 'json',
data:JSON.stringify(formData),
success:function(data,status,xhr){
console.log('saved successfully');
},
error:function(data,status,xhr){
console.log('error occured'); // This gets printed
}
});
控制器
@PostMapping(value="/ajax/send")
public void sendSupportMessage(@RequestBody SupportConversationDTO supportConversationDTO) {
supportConversationService.save(supportConversationDTO);
return;
}
答案 0 :(得分:1)
在ajax请求中,您使用的是dataType:'json'
,jQuery’s Ajax-Related Methods描述
// The type of data we expect back
dataType : "json",
但是从您的控制器中,您将返回void !!!
您需要更新ajax请求,删除dataType
并更新success:function
$.ajax({
type : 'POST',
contentType: "application/json",
url : url,
data:JSON.stringify(formData),
success:function(data) {
console.log('saved successfully');
},
error:function(data,status,xhr) {
console.log('error occured');
}
});
然后更改您的控制器代码,从中返回内容并添加@ResponseBody
@PostMapping(value="/ajax/send")
@ResponseBody
public String sendSupportMessage(@RequestBody SupportConversationDTO supportConversationDTO) {
supportConversationService.save(supportConversationDTO);
return "success";
}