Lee wrote:
Hi,
I am using a simple Ajax script to access a template file that consists
of this:
<tr>
<td>{var1}</td>
<td>{var2}</td>
<td>
<table>
<tr>
<td>Name: {name3}</td>
<td>Age: {age3}</td>
</tr>
</table>
</td>
</tr>
I want to use it to add another row to a table, but I understand that I
should be using insertRow and insertCol methods instead of just using
table.innerHTML.
If your returned text is JSON text, say:
{
var1 : 'some value',
var2 : 'some other value',
name3 : 'a name',
age3 : 'age for name 3'
}
And your template is as specified, then you can use
getElementsByTagName to get the TDs, then loop through them. Where the
content matches an object property, insert the value, something like:
var oRow = rowTemplate.cloneNode(true);
var cell, cells = oRow.getElementsByTagName('td');
var cellContent;
var obj = eval('(' + jsonText + ')');
for (var i=0, len=cells.length; i<len; i++){
cell = cells[i];
if (/{[^}]+}/.test(cell.innerHTML)){
cellContent = cell.innerHTML.replace(/[{}\s]/g,'');
if (cellContent in obj){
cell.innerHTML = obj[cellContent];
}
}
}
Completely untested, it's just to give you an idea. Once you've got
your modified row, you must append it to a tbody element to keep IE
happy. If you already have a table and only have one tbody, then:
var tbody = tableRef.getElementsByTagName('tbody')[0];
tbody.appendChild(oRow);
Is there a good way to extract the tags so that I can use these
methods? Or even just a way to put these tags into a multidimensional
array? I couldn't find any such libraries to do this, but I'm pretty
sure I'm going to have to use regular expressions.
Don't try to use innerHTML to replace part of a table, use it only
replace either the entire table or the content of a cell. Using
innerHTML and a regular expression means you will have to use a replace
for every property you want to replace, which means parsing the entire
string every time. It may get very slow as the template gets bigger.
--
Rob