ajax html
in Programming on jQuery
jQuery
Ajax (html)
View (list_ajax.jsp)
<%
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/text","root","1234");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM test order by idx desc";
ResultSet rs = stmt.executeQuery(sql);
Map<String,Object> object = null;
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
while(re.next()){
int idx=rs.getInt("idx");
String content = rs.getString("Content");
object = new HashMap<String,Object>();
object.put("idx",idx);
object.put("content",content);
list.add(object);
request.setAttribute("list", list);
}
rs.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{if(stmt!=null) {stmt.close();}}catch(SQLException e){}
try{if(conn!=null) {conn.close();}}catch(SQLException e){}
}
%>
<c:choose>
<c:when test="${fn:length(list) > 0}">
<c:foreach items="${list }" var="list">
<tr>
<td width="30%">
${list.idx}
</td>
<td>
${list.content}
</td>
</tr>
<c:forEach>
</c:when>
<c:otherwise>
<tr>
<td colspan="2">
no data
</td>
</tr>
</c:otherwise>
</c:choose>
ajax.html
<html>
<head>
<script type="text/javascript" src="/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function(){
$.ajax({
// form action(url), type(method)
// ajax needs data type even though form doesn't need.
url : '/list_ajax.jsp',
type : 'GET',
dataType : 'html',
/* data : {}, */
success : function(data){
$("table").html(data);
}
});
$("#submitButton").click(function()){
$.ajax({
// form action(url), type(method)
// ajax needs data type even though form doesn't need.
url : '/insert_ajax.jsp',
type : 'POST',
dataType : 'html',
//parameter
//data : {content : $("input[name=content]").val()},
// to send a form, name value is must-have
data : $("form").serialize();
success : function(data){
$("table").html(data);
}
})
})
</script>
</head>
<body>
<form action="/insert.jsp" method="post" id="frm">
<input type="text" name="content" />
<input type="button" id="submitButton" value="submit" />
</form>
<table width="100%" border="1"></table>
<body>
</html>
Server side (/insert_ajax.jsp)
<%
String content = request.getParameter("content");
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/text","root","1234");
String sql = "insert into test(content) values(?)";
pstmt = conn.createStatement();
pstmt.setString(1,content);
pstmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
try{if(pstmt!=null) {stmt.close();}}catch(SQLException e){}
try{if(conn!=null) {conn.close();}}catch(SQLException e){}
}
response.sendRedirect("/list_ajax.jsp");
%>