Spring MVC Ajax Post 400错误(错误请求)
因此,我正在使用SpringMVC,我正在尝试做一篇ajax文章,向一个Spring MVC Ajax Post 400错误(错误请求),ajax,spring-mvc,Ajax,Spring Mvc,因此,我正在使用SpringMVC,我正在尝试做一篇ajax文章,向一个post实体添加comment,就像典型的社交网络一样。我在Chrome开发者的工具中得到一个错误,它说加载资源失败:服务器响应状态为400(错误请求)。我想这可能意味着我的控制器出了问题,但是设置的方式不允许我在调试模式下检查它 我将向你们展示所有一起工作的代码片段,这样你们就可以更好地理解我的问题 这是我的Ajax,所有内容都在运行,并发送一条“有一个错误”消息,所以它至少在运行代码并到达控制器 另外,CDATA内容也适
post
实体添加comment
,就像典型的社交网络一样。我在Chrome开发者的工具中得到一个错误,它说加载资源失败:服务器响应状态为400(错误请求)
。我想这可能意味着我的控制器出了问题,但是设置的方式不允许我在调试模式下检查它
我将向你们展示所有一起工作的代码片段,这样你们就可以更好地理解我的问题
这是我的Ajax,所有内容都在运行,并发送一条“有一个错误”消息,所以它至少在运行代码并到达控制器
另外,CDATA
内容也适用于Thymeleaf
<script th:inline="javascript">
/*<![CDATA[*/
var postById = /*[[${postById.id}]]*/'1';
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#submit").on("click", function(ev) {
ev.preventDefault();
$.ajax({
url : "newComment",
type : "post",
data : {
"postById" : postById,
"newComment" : $("#newComment").val()
},
success : function(data) {
console.log(data);
location.reload();
},
error : function() {
console.log("There was an error");
//location.reload();
}
});
});
});
/*]]>*/
</script>
另外,我在实体对象中有一些注释,可能与此有关
这是我的用户实体
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
@JsonManagedReference
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
这里还有一张Chrome开发者工具中我的控制台的图片,所以你们可以看到它到底向我展示了什么
如果有人能看到我错在哪里,并为我指出正确的方向,那就太好了,提前谢谢
另外,如果你们需要查看任何其他代码,请告诉我。我的问题在Ajax中,我在寻找
postById.id
,而我本应该只使用我在控制器的Get方法中添加到模型中的postId
@RequestMapping(value="viewCourse/post/newComment", method=RequestMethod.POST)
public @ResponseBody Post newComment (@Valid @RequestParam Long postId, @RequestParam String newComment, ModelMap model, @AuthenticationPrincipal User user)
{
Post post = postRepo.findOne(postId);
Comment comment = new Comment();
comment.setComment(newComment);
comment.setPost(post);
comment.setDate(LocalDate.now());
comment.setTime(LocalTime.now());
comment.setDateTime(LocalDateTime.now());
comment.setUser(user);
user.getComments().add(comment);
post.getComments().add(comment);
commentRepo.save(comment);
Post savedPost = postRepo.save(post);
return savedPost;
}
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
@JsonManagedReference
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
@ManyToOne
@JsonBackReference
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}