1

I am sorry if it is a simple problem for you.But i am really struggling with this problem

In our application we have plenty of ajax calls in each and every page. We are using jQuery ajax. Presently what we are doing is

When we get the result from like myresults, we are passing to a function populate where we are building the result.

function populate(myresults)
{        
    var str='<table>';       
    for(var i in myresults){
        str+='<tr>';
        str+=myresults[i].name;
        str+='</tr>';    
    }
    str+='</table>';

    $('#divId').html(str);
}

Not exactly we are building tables in all places. The code is working perfectly, but I think writing of code like this is not the right approach. How can I can beautify my code. I can use jQuery or javascript.

PSR
  • 39,804
  • 41
  • 111
  • 151

4 Answers4

1

You should try to look for TemplateEngine - it could allow to decrease code count and make it more clear. What Javascript Template Engines you recommend?

Community
  • 1
  • 1
Dmitry Volokh
  • 1,630
  • 16
  • 28
1

You should run your code through a linting engine like JSLint or JSHint and you should familiarize yourself with good practice.

Here's one way (of more than one possible solution) to optimize your code:

function populate(myresults) {
    var table = $(document.createElement('table'));       

    $(myresults).each(function (i) {
        var row = $(document.createElement('tr')),
            cell = $(document.createElement('td')).text(myresults[i].name);
        row.append(cell);
        table.append(row);
    });

    $('#divId').append(table);
}
Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
  • `var table = $(document.createElement('table'));` there are some typos on the code... missing the `)` closing in the jquery selectors. – a--m Apr 29 '13 at 12:05
0

Maybe, creating a new DOM element more correct ?

Like this:

function populate(myresults)
  {        
   var str= $('<table />)';       
      for(var i in myresults){
        str.append($('<td />').text(myresults[i].name).appendTo($('<tr />')));
      }
    $('#divId').empty().append(str);
  }
Kirill
  • 19
  • 5
0

You could do it this way:

function populate(myResults)
{        
    var tab = $('<table />');       
    for(var i in myResults){
      if (myResults.hasOwnProperty(i)) {
          var tr = $('<tr />');
          tr.append($('<td /'>, {text: i.name}));
          tab.append(tr);
      }
    }
    $('#divId').append(tab);
}

Using a template engine as suggested by the others would be preferable as it's a better, more maintainable approach.

Vimal Stan
  • 2,007
  • 1
  • 12
  • 14