开发者

Trouble build a table from json file under a div

开发者 https://www.devze.com 2023-02-23 02:27 出处:网络
I need to get rather complicate JSON data from (large) JSON file into a table at a specific part of a page. Somehow when I ran my code, nothing happens.

I need to get rather complicate JSON data from (large) JSON file into a table at a specific part of a page. Somehow when I ran my code, nothing happens.

Snap shoot of purchase.json file -

{ "table": { "purchases": [ { "First Name": "Joe", "Last Name": "Jenson", "Product": "Netbook Computer", "Price": "356", "Purchase Date": "04/04/2011", "Unit Count": "1", "Type": "Computer", "Return Date": "05/03/2011", "Seq. No.": "0" }, { "First Name": "Christy", "Last Name": "Davis", "Product": "iPad", "Price": "656", "Purchase Date": "开发者_如何学编程04/07/2011", "Unit Count": "1", "Type": "Computer", "Return Date": "05/06/2011", "Seq. No.": "10" }, { "First Name": "Justin", "Last Name": "Gill", "Product": "Laptop Computer sleeve", "Price": "699", "Purchase Date": "04/02/2011", "Unit Count": "1", "Type": "Computer Assesory", "Return Date": "05/01/2011", "Seq. No.": "20" } ] } }

The html file - JSON to table

get json file "purchase.json"

Parse the array into a table and load it in AJAXDiv

Table header has to be pulled from the key in the key:value pair found in the JSON.

The JavaScript code I have is - $(document).ready(function() { //Retrieve the JSON data from the server using AJAX $('#AJAXButton').click(function() { $.getJSON('data/purchase.json', function(data) { processJSON(data); }); });

//Process and display the JSON data
function processJSON(jsondata) {
    var output = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"><thead><tr>';

    // retrieve the keys and place into an array
    var keys = objKeys(jsonData.table.loans[0]).join("|");          
    var keyData = splitString(keys);

    // print header
    for (var i = 0; i < keyData.length; i++)
    {
        output += "<th>" + keyData[i] + "</th>"; 
    }           
    output += "</thead></tr><tfoot>";

    // print footer
    for (var i = 0; i < keyData.length; i++)
    {
        output += "<th>" + keyData[i] + "</th>"; 
    }   
    output += "</tfoot></tr><tbody>";   

    // print content of the json array in tbody
    for(var j=0, jj = jsonData.table.loans.length; j < jj; j++)
    {
        for (var k = 0, kk = keyData.length; k < kk; k++)
        {
            var current = keyData[k];
            output +="<td>" + jsonData.table.loans[j][current] + "</td>"; 
        }
        output += "</tr>";
    }

    output += "</tbody></tr></table>";
    //Loop through the Languages 

    $('#AJAXDiv').html(output);
}


// get json keys
function objKeys(obj) 
{
    var keys = [];
    var i = 0;
    for (var z in obj) 
    {
        if (obj.hasOwnProperty(z)) {
            keys[i++] = z;
        }
    }
    return keys;
}

// split string into array
function splitString(myString)
{
    var mySplitResult = myString.split("|");
    return mySplitResult;
}

});


It may be that you have a variable missing, there's

function processJSON(jsondata)

But you later use

jsonData.table.loans[0] //etc....

I suggest using a debugger like Firebug or DevTools, it makes problems like this much easier to catch.


You can also use this library: Json-To-Html-Table


I use this script that i coded my self, it really builds any json table from a mysql result o whatever the MySQL is outputting, you can rename the column names with your own labels, by the output order. Also if you give none, the default names will be generated. It used the $post Jquery plugin-in which you can add easly with 1 line of code.

all you need is the div with table_result:

  function dyna_query(label){

        $.post("your_mysql_query.php",{post_limit:15},function(e){
        if(e=="fail"|| e=="" ||e=="[]"){return;}


        var obj=JSON.parse(e);
        //get default column names based on the associative object JSON
    var column_n=Object.keys(obj[0]).length/2;
    var c_names=Object.keys(obj[0]).splice(column_n,column_n);
        //if there are labels, then these will replace others.

      if( label){c_names=label.split(",");}

        var table_row="";
        //initialize table 
        var table_format="<table  border=0><tr>"; 

      for(var r=0; r<c_names.length;r++){
        table_row+="<td class=table_h>"+c_names[r]+"</td>";}
        table_row+="</tr>";

      for(var i=0; i<obj.length;i++){table_row+="<tr>";
      for(var c=0; c<c_names.length;c++){table_row+="<td class='table_bb'>"+obj[i][c]+"     </td>";}table_row+="</tr>";}

        //get all the other fields and rows
        table_format+=table_row+"</table>";
        //buld the html for the div with the id table_result
        $("#table_result").html(table_format);

    });
    }

now simply call dyna_query("c1, c2, c3"); //renames default column names or dyna_query(); for full output with default labels

0

精彩评论

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