JSP + JavaScript: templating
I have a server-side HTML templating with JSP + JSTL, which generates, say, a table with some user data:
<body>
...
<table>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.department}</td>
</tr>
</c:forEach>
</table>
...
</body>
This is a template number 1.
The user can submit new data to the server through the form. The data is sent by AJAX, and upon successfull request it should be dynamically appended to the table without any page reload.
To append the data, I need to use a template number 2, which is encapsulated inside JavaScript or is present at开发者_Go百科 the HTML page with "display: none;" and "class='template'".
<tr class="template" style="display: none;">
<td>%user.name%</td>
<td>%user.age%</td>
...
</tr>
...
<script>
$(".template").clone().fillTheTemplateAndAppendToTheTable(user); //just to explain
</script>
The question: can I avoid HTML code duplication and have only one single template in this case? If yes, how to do that?
You could do the following:
Template 1:
<body>
...
<table id="userTable">
<c:forEach items="${users}" var="user">
<%@include file="userRow.jsp" %>
</c:forEach>
</table>
...
</body>
userRow.jsp:
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.department}</td>
</tr>
The action displaying the full table would forward to the first template, and the action handling the ajax call would forward to userRow.jsp.
And in your ajax callback, simply append the HTML received from the server (i.e. the result of the execution of userRow.jsp) at the end of your table. In JQuery, it would look like this (where createUser.action
is the action that creates the new user based on the parameters passed through the user
JavaScript object, and then forwards to userRow.jsp
to render the newly created user):
function createUser(user) {
$.get("createUser.action", user, ajaxCallbackWhichAddsANewUserToUserTable);
}
function ajaxCallbackWhichAddsANewUserToUserTable(newUserRow) {
$("#userTable").append(newUserRow);
}
精彩评论