I'm trying to find the most reasonable way to dynamically show a lot of HTML after an AJAX call. We currently get a json array and then just create a string of HTML including the array values, then spit that all to $("#ele").html(), but the string is huge.
And that's the concern; we've got a good 100 lines of <div>
s and <spans>
, etc. in a javascript variable, Which makes the jquery string to dynamically insert a new order entry big and ugly, like below:
var newEntry = "<div class='sale-box' id='saleBox"+respObj[i]["id"]+"'>"
+"<div style='width: 100%; float: left;'>"
+"<b><center>Invoice Number "+respObj[i]["invoiceNumber"]+"</b>"
+"<a href='https://www.bluescentric.com/mgmt/log-entries.php?i="+respObj[i]["id"]+"'>"
+" <i>(See History Log)</i></a></center>"
+a hundred more lines... literally.
Is there a better way to display a large amount of HTML from javascript? Right now, it seems our two options are 1) just having the php create the whole "" structure and sending that to javascript, or 2) taking the array variables and plug them into a big, long javascript string that we then output to an element?
Use a templating system or create a simple template system. Use the function get_file_contents
of an html file that contains something like this:
<table><tr><td>{{column_1}}</td><td>{{column_2}}</td></table>
And then use javascript as an ajax request to retrieve the file and use something like
var template = "string of template from php";
var interpolated_template = template.interpolate({column_1:'something',column_2:'something2'});
interpolate
is a String.prototype.interpolate = function ...
prototype function extending String, so any string can interpolate variables using the syntax "String".interpolate(args_as_object)
:-)