开发者

jQuery and JSON: break object into a table

I need a little bit of help navigating through this object:

{"COLUMNS":["ID","TYPE","NAME"],"DATA":[[1开发者_开发百科,"Image","My Image"],[2,"Text","My Text"],[3,"Video","My Video"],[4,"video","test"],[5,"Image","testName"],[6,"Image","testName"],[7,"Image","testName"],[8,"Image","testName"],[9,"Image","testName"],[10,"Image","testName"]]}

What would be the best way to loop over this object in order to display it like so:

ID  | Type   | Name
1     Video    My Video
...   ...      ...

This JSON object is clearly a query result... a lot of queries will need to be displayed as tabular data like this, so perhaps I should create a class (function) that handles this result.


headers = obj["COLUMNS"];
$(headers).each(function(index,item){ /* do something interesting */ });
data    = obj["DATA"];
$(data).each(function(index,item){ /* do something interesting */ });

"Something interesting" in this case would be to create new TH and TD elements from the headers, TR and TD elements from the data rows.

(You could of course do

$(obj["COLUMNS"]).each(...)

if you don't need the headers and data separately later. Sometimes I think people go a little overboard with the functional model, sacrificing clarity.)


So thanks to Charlie Martin, I put together a nice little function that will take the result of the query and create a table using jQuery:

function createTable(result) {

    var headers = result["COLUMNS"];
    var data = result["DATA"];      
    var tableHeader = "<table><thead><tr>";
    var tableBody = "<tbody>";
    var endTable = "</table>";

    $(headers).each(function(index,item){
        //alert("HEADER: " + item);

        tableHeader += "<th>" + item + "</th>";     

    });

    tableHeader += "</tr></thead>";
    $(tableHeader).appendTo("#placeholder");

    $(data).each(function(index,item){
        //alert("DATA: " + item);

        tableBody += "<tr>";

        $(item).each(function(index, secitem) {
            tableBody += "<td>" + secitem + "</td>";
        });

        tableBody += "</tr>";

    });

    tableBody += "</tbody>";

    $(tableBody).appendTo("#placeholder");              
    $(endTable).appendTo("#placeholder");

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜