我想使用AJAX将URI值发送到数据库,请求是用@Controller编写的。但是当我点击提交的时候,数据库里什么都没有。例如,我有一个地址:
http://localhost:8080/post/view/2如上所述,我想在每次单击submit时将值2保存到我的数据库中。我试过了,但一无所获
@Controller
@RequestMapping(value="post/view/{id}", method= RequestMethod.POST, produces = "apllication/json")
public @ResponseBody Comment newComment (@RequestParam(name="id") Long id) {
Comment comment = new Comment();
Post postView = postService.findById(id);
comment.setPoster(postView);
commentService.create(comment);
return comment;
}和我的代码HTML
view.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head >
<script type="text/javascript" language="javascript"
src="https://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript"
src="https://www.technicalkeeda.com/js/javascripts/plugin/json2.js">
</script>
<title th:text="${postView.title}">View Post</title>
<script >
function madeAjaxCall(){
$.ajax({
type: "post",
url: "http://localhost:3313/post/view/{id}"
}
</script>
</head>
<body>
<div>
<form method="post" >
<main id="posts">
<article>
<h2 class="title" th:text="${postView.title}">Post Title</h2>
<div class="date">
<i>Posted on</i>
<span th:if="${postView.author}" th:remove="tag">
<i>by</i>
<span th:text="${ postView.author.lastName}">Svetlin Nakov</span>
</span>
</div>
</article>
<input type="button" value="Ajax Submit" onclick="madeAjaxCall();"/>
</main>
</form>
</div>
</body>
</html>我想我在AJAX或@Controller上错了或者漏掉了什么。谢谢
发布于 2020-10-22 16:28:04
尝试使用@PathVariable而不是@RequestParam
发布于 2020-10-22 23:52:22
我注意到你的代码中有几个地方是错误的:
https://www.technicalkeeda.com/js/javascripts/plugin/jquery.js此链接无效。尝试从官方网站:https://code.jquery.com/jquery-3.5.1.js使用jQuery
url: "http://localhost:3313/post/view/{id}"。请确认端口为3313,并提供有效的{id}值。而且,你根本不需要使用端口和url。请参阅下面的代码:produces = "apllication/json"你这里有打字错误。只需将其更改为produces = MediaType.APPLICATION_JSON_VALUEid参数。查找@RequestParam和@PathParam之间的区别。(@RequestParam(name="id") Long id) {您应该使用@PathVariable下面是一个有效的代码:
后端控制器:
@PostMapping(value = "/post/view/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
void newComment(@PathVariable Long id) {
System.out.println("Requested with id = " + id);
}前端:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<body>
<script>
function madeAjaxCall() {
$.ajax({
type: "post",
url: "/post/view/5"
})
}
</script>
<input type="button" value="Ajax Submit" onclick="madeAjaxCall();"/>
</body>
</html>https://stackoverflow.com/questions/64478084
复制相似问题