我试图将数据发布到servlet,然后将其插入到mysql数据库中。
这是html表单:
<form id="commentForm" name="commentForm" action="http://server.co.uk/dbh" method="POST">
<input type="text" name="name" placeholder="Your name" required="required">
<textarea name="comment" placeholder="Enter your comment here" required="required"></textarea>
<input type="hidden" name="postID" id="postID" value="<%= postID %>">
<input type="submit" name="submit" id="commentSubmit" value="submit">
</form>
Jquery:
$("#commentSubmit").click(function(e){
var postData = $("#commentForm").serializeArray();
var formURL = $("#commentForm").attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#commentFormWrap").html("<p>Success</p>");
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#commentFormWrap").html("<p>error: "+errorThrown+"</p>");
}
});
e.preventDefault(); //STOP default action
$("#commentForm").hide();
});
简化的dbh servlet:
import javax.servlet.annotation.WebServlet;
...
@WebServlet(description = "Handles connection to MySql database", urlPatterns = { "/dbh" })
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
postArray = request.getParameterValues("postData");
commentName = postArray[0];
comment = postArray[1];
postID = Integer.parseInt(postArray[3]);
try{
submitComment();
}catch(Exception e){
e.printStackTrace();
}
}
public void submitComment() throws Exception{
try{
sql="INSERT INTO crm_comments (comment_name, comment_content, comment_date, post_id) VALUES (?, ?, NOW(), ?)";
prep = conn.prepareStatement(sql);
prep.setString(1, commentName);
prep.setString(2, comment);
prep.setInt(3, postID);
rs = prep.executeQuery();
}catch(Exception e){
e.printStackTrace();
}
}
目前,ajax
调用正在返回错误块error:
。但是没有errorThrown
变量。
从我可以看到servlet正确编写。 html
和Jquery
ajax
调用之间是否有问题,它是否未将数据发布到servlet?
答案 0 :(得分:2)
postArray = request.getParameterValues("postData");
我认为你可以用实际字段名称替换它
commentName = request.getParameter("name");
comment = request.getParameter("comment");
这将解决您的问题
答案 1 :(得分:1)
根据jQuery documentation,serializeArray
方法返回JavaScript对象数组。此方法将从form
生成一个JSON对象,其外观如下:[{"name":"name",value:"<your name input value>"},{"name":"comment",value:"<your comment>"},{"name":"postID",value:"<postID value>"} ...]
。只会发送postData
变量的内容:您根本不会对Servlet中的postData
关键字有任何引用。
因此,在您的Servlet中,request.getParameterValues("postData");
调用似乎无效。试试这个:
commentName = request.getParameterValues("name");
comment = request.getParameterValues("comment");
postID = Integer.parseInt(request.getParameterValues("postID"));