开发者

Build Json Object then relate the results to HTML table data

I pass out a ajax get which contains a parameter i.e. date added to db.

Java queries the DB for results of persons added on this date, and builds a JSON object for me like so:

{
  "resultdata" : { "rowsReturned" : "2", "fetchTime" : "180"}
  "row_1" : { "name" : "Larry", "sex" : "m", "age" : "26", "location" : "seattle" }
  "row_2" : { "name" : "Pedro", "sex" : "m", "age" : "22", "location" : "unknown" }
}

I can then return the JSON object as a String. I'd then like to dynamically build a table based on these results.

First of all is the JSON object correct for building a table?

The result data tells me how many rows and the time taken in milliseconds, followed by however many rows in that particular format.

I then want to create a table inside a specific div element once these results are returned to my browser on the fly with no page refreshes etc.

so Id expect Table headers with titles of each column - followed by you guessed it 开发者_Python百科2 rows.

How is the best way to go about doing this. I am familiar with jQuery, JSON is totally new to me and dealing with JSON in jQuery is something i'm keen on learning.

Any help is much appreciated.


you can use jsonlint to validate your json. Yours is not valid. It's missing some ',':

{
    "resultdata" : {
        "rowsReturned" : "2",
        "fetchTime" : "180" 
    }, // <--
    "row_1" : {
        "name" : "Larry",
        "sex" : "m",
        "age" : "26",
        "location" : "seattle" 
    }, // <--
    "row_2" : {
        "name" : "Pedro",
        "sex" : "m",
        "age" : "22",
        "location" : "unknown" 
    }
}

I've made a little DEMO of one possible way how to loop through the json with for-in-loops


for (key in json) { 

loops through the json and stores each key in the 'key' variable. in your case 'resultdata','row_1','row_2'.
So to access the data for each key you write json[key] which translates to json['row_1'] for example.
Now you do the same thing for the row_1 object with:

for(key1 in json[key])

key1 are now the keys in the row_1 object: 'name','sex',...

to access the data now you'll write json[key][key1] which would be json['row_1']['name'] for example.

of course it's advisable to give the keys meaningful names to avoid confusion like in my example:)


Your JSON looks fine for building a table.

You'll want to use $.getJSON() to fetch the JSON data, as it will automatically parse the JSON into an object for you. If you need the advanced features of $.ajax(), you can call $.parseJSON() on the returned data from the AJAX call and it will parse the JSON into an object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜