Using a java servlet, I've been doing the same approach to building or updating HTML. I create the basic table on the HTML page, then call for the body from the servlet with ajax.
As an example: HTML
<div id="divLocationMain" style="margin-top: 2%;">
<table style="width: 99%;">
<thead>
<tr>
<th>Clinic</th>
<th>Location</th>
<th>Clinic</th>
<th>Location</th>
</tr>
</thead>
<tbody id="tbodyAdminLocation" style="font-size: small;">
</tbody>
</table>
</div>
javascript
function updateLocationTable() {
$.ajax({
url: 'TCAUServlet',
type: 'POST',
data: {formType: "getLocationTable"},
dataType: 'html',
success: function (responseText) {
$('#tbodyAdminLocation').html('');
$('#tbodyAdminLocation').html(responseText);
},
error: function (request, status, error) {
alert("An error occurred. Error: " + status + ", " + error);
}
});
}
Servlet
private String getLocationTable() throws ClassNotFoundException, SQLException {
List<Location> locList = TCAUDatabaseUtil.getLocations();
Collections.sort(locList, new LocationComparator());
String htmlString = "";
for (int x = 0; x < locList.size(); x++) {
Location loc = locList.get(x);
htmlString += " <tr>\n"
+ " <td>" + loc.getLocationClinic() + "</td>\n"
+ " <td>" + loc.getLocationName() + "</td>\n";
if (x < locList.size() - 1) {
loc = locList.get(++x);
htmlString += " <td>" + loc.getLocationClinic() + "</td>\n"
+ " <td>" + loc.getLocationName() + "</td>\n";
}
htmlString += " </tr>\n";
}
return htmlString;
}
It works well, but I can't help but wonder if there isn't a better/easier/more efficient way, especially when I'm dealing with objects with quite a few fields in them.
$('#tbodyAdminLocation').html('');is redundant ashtml(content)will replace the innerHTML of element, there is no need to first empty it. In Java, no need to add spaces just to indent the code inhtmlString.\nhas no effect(just adds space) in DOM thus, can be removed. \$\endgroup\$