1
我正在嘗試創建一個論壇,在提交表單時應將帖子保存到數據庫中並顯示在表單下方。 它正在保存到數據庫中,但只有在我們重新加載頁面後纔會顯示。我們提交表單時是否有某種方式?如何從jsp頁面獲得響應而無需重新加載?
<%@ page import="java.sql.*"%>
<%@page import="org.json.*"%>
<%
System.out.println("Start");
String value = request.getParameter("jsonData");
JSONObject newObj = new JSONObject();
try {
newObj = new JSONObject(request.getParameter("jsonData"));
} catch (JSONException e) {
e.printStackTrace();
}
String title = "";
String tag = "";
String postData = "";
try {
title = newObj.getJSONObject("mydata").getString("title");
tag = newObj.getJSONObject("mydata").getString("tag");
postData = newObj.getJSONObject("mydata").getString("postData");
} catch (JSONException e) {
e.printStackTrace();
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=true", "root", "1111");
//System.out.println(con);
PreparedStatement ps = con.prepareStatement("insert into forumdb.userpost(title,post,tag) values(?,?,?)");
ps.setString(1, title);
ps.setString(2, postData);
ps.setString(3, tag);
ps.executeUpdate();
con.close();
} catch (Exception e) {
}
System.out.println("End");
response.setContentType("text/html");
response.getWriter().write("success");
%>
var request;
function postArticle() {
var title=document.postform.title.value;
var postDescription = CKEDITOR.instances.postDescription.getData();
var tag=document.postform.tag.value;
var myData = {"mydata": {"title": title, "tag": tag, "postData":postDescription}};
$.ajax({
type: "POST",
url: "/forum1/index.jsp",
data: {jsonData: JSON.stringify(myData)},
dataType: "json",
success: function(){
if(success==false)
{ location.reload(); }
}
});
}
你可以使用ajax。 –
http://stackoverflow.com/questions/9280345/updating-contents-of-a-jsp-page-without-refreshing 試試這個,它有相同的概念。 –