I am new to Javascript and Jquery.
I am using Jquery $.ajax for sending get request, dealing with returned Json String and use .html() to display contents in <div id="myTabs"></div> in my html. You can see from my code below, I am using a String variable to make a HTML list. Am I doing this in a good practice? I feel this way is not very agile, Is there any better way of doing this?
Thanks!
function updateRelated(str)
{
$.ajax(
{
url:ServerUrl+api_subject,
type:'GET',
success:function(json)
{
// alert(json);
var obj = jQuery.parseJSON(json);
var toDisplay="";
var tableDisplay="<ul>";
for(var i=0;i<obj.subject_list.length;i++)
{
tableDisplay=tableDisplay+'<li><a href="subject.htm?subjectid='+obj.subject_list[i].id+'">'+obj.subject_list[i].title+'</li>';
// toDisplay=toDisplay+"<br>preferred_synonym:"+obj.relatedCocepts[i].preferred_synonym+",Type: "+obj.relatedCocepts[i].type+",score: "+obj.relatedCocepts[i].score;
}
tableDisplay=tableDisplay+"</ul>"
$("#myTabs").html(tableDisplay);
}
}
)
}
basically i’m reading your question to be really asking whether or not you should be writing a string of markup and outputting it into the dom, with variables concatted into it.
Its ok to do for smaller stuff, but if you’re writing a lot of views with javascript, you’ll want a tool for putting together view partials.
There are tools out there that do this: