Pregunta

I'm using jQuery templating which is taking JSON data to create a table. This code is working fine. But when I try to create a function around this code and pass JSON data to it which I'm getting from an AJAX request, it shows the values in the console but not in the table. Working code with dummy data is:

var json = [{"class":12,"marks":"500","marks1":"200","marks2":"300"},{"class":11,"marks":"200","marks1":"300","marks2":"400"}]

$.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');  

for(var i=0; i<json.length; i++){   
    $.tmpl('kList',json[i]).appendTo("#table1")
}

Here is the code where I'm warping the upper code in function and passing the JSON data as a parameter that shows the values in console when I print it with console.log(json) but not filling the table. The JSON parameter is having the same JSON data as in above code.

function dataTable(json){
    console.log(json); // here json values are appearing in the console
    $.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');  

    for(var i=0; i<json.length; i++){   
        $.tmpl('kList',json[i]).appendTo("#table1")
    }
}

Please help me out because I don't know whats wrong in this code. Thanks in advance.

¿Fue útil?

Solución

Your json parameter is a string. You should convert it to an object, using $.parseJSON(json).

Take a look at this for conversion detail.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top