我想使用AJAX请求将表单中的数据添加到数据库中。调用发生更改的页面的控制器接受'事件'参数
@RequestMapping(value = "/event")
public ModelAndView event(HttpServletRequest request, HttpSession session)
{
ModelAndView modelAndView = new ModelAndView();
SimpleUser simpleUser = simpleUserService.findById((Integer) session.getAttribute("userId"));
Profile profile = simpleUser.getProfile();
modelAndView.addObject("nameOfEventOwner", profile.getName());
modelAndView.addObject("surnameOfEventOwner", profile.getSecondName());
int id = Integer.parseInt(request.getParameter("event"));
System.out.println(id);
modelAndView.addObject("event", eventService.findById(id));
modelAndView.setViewName("eventpage");
return modelAndView;
}
在页面上有一个表单,我要从中输入数据的数据(稍后在页面上动态显示)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Yura
Date: 10.05.2017
Time: 15:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script src="<c:url value="/resources/jquery-3.2.1.min.js" />"></script>
<script>
function call() {
var comment = $("#comment").val();
var rate = $("#rate").val();
$.ajax({
url : "/addcomment",
method : 'GET',
data : {
comment : comment,
rate : rate,
idEvent: ${event.getId()},
idAuthor: ${sessionScope.simpleUser.getId()}
},
dataType: "html",
success : function(results){
alert("add");
}
});
};
</script>
<title>Title</title>
</head>
<body>
owner: ${nameOfEventOwner} ${surnameOfEventOwner}
<br>${event.getNameOfEvent()} <pre> ${event.getDateOfEvent()}}</pre>
<br> ${event.getDescription()}
<br> ${event.getTag()}
<br>
<form>
Commentary: <input type="text" id="comment" placeholder="text">
Rating: <input type="text" id="rate" placeholder="rating">
<button type="submit" id="button" onclick="call()">Add commentary</button>
</form>
</body>
</html>
我想通过AJAX将这些值传递给控制器。但是当我传递值时,我的页面会重新加载,并且我被NumberFormatExseption错误所破坏,因为&#39; event&#39;参数未初始化。我该如何解决这个问题?
答案 0 :(得分:0)
将按钮类型更改为“按钮”。
当类型为“提交”时,操作将尝试提交重新加载页面的表单。
使用“按钮”类型,您只需将操作委派给call()
功能。
<button type="button" id="button" onclick="call()">Add commentary</button>