jquery - JSON to <table>
I have Json of the form
[{"id":39,"data":1},{"id":40,"data":2}]
It does not parse properly with jQuery.pa开发者_运维问答rseJSON()
I need to take this data and create a html table
. I was thinking of creating the HTML dynamically in the js.
A. How can I parse the json?
B. Is dynamic html the best route?Update
I apologize. Evidently my question is not clear. Here is the jquery $.get('Service.aspx',
{ p1: value, p2: value },
function (data) {
notesJson = data;
alert(notesJson);//Json comes back as I said here...
var noteSet = jQuery.parseJSON(notesJson);
alert(noteSet.notes);
});
notes does exist in the Json. The second alert fails "undefined".
Ok based on you comment on your question:
Use $.getJSON
instead of $.get
:
$.getJSON('someurl', {/*somedata*/}, function(json_data){
//no need for parsejson
//use the json_data object
var table_obj = $('table');
$.each(json_data, function(index, item){
var table_row = $('<tr>', {id: item.id});
var table_cell = $('<td>', {html: item.data});
table_row.append(table_cell);
table_obj.append(table_row);
})
})
What you have is an array, you need an object. Try
{ "notes" : [{"id":39,"data":1},{"id":40,"data":2}] }
as the json
or do this
alert(noteSet[0]);
alert(noteSet[1]);
Here's another good library to simply achieve that: https://github.com/afshinm/Json-to-HTML-Table
Just pass the JSON data to this library and get the HTML table:
//Only first parameter is required
var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');
You say you're using .NET so you could use
return Json(yourObject, JsonRequestBehavior.AllowGet);
instead of JavaScriptSerializer. You won't have to parse it.
A jquery plugin that accepts JSON data to fill a table could do. jsonTable
Here's another way taking into account the headings of the table for a typical database query. Based on Neil's answer:
$.getJSON('bower.json', {}, function(json_data) {
var table = $('table');
$.each(json_data, function(key, item) {
var table_row = $('<tr>');
$.each(item, function(itemKey, itemValue) {
if (key == 0) {
table.append($('<th>', {html: itemKey}));
}
table_row.append($('<td>', {html: itemValue}));
});
table.append(table_row);
});
});
Try this full code:
<head>
<script type="text/javascript">
$.getJSON('URL', function(json_data){
var table_obj = $('table');
$.each(json_data, function(index, result){
var table_row = $('<tr>', {});
var table_cell1 = $('<td>', {html: result.firstName});//result.yourDataAttributes
var table_cell2 = $('<td>', {html: result.lastName});
var table_cell3 = $('<td>', {html: result.age});
table_row.append(table_cell1,table_cell2,table_cell3);
table_obj.append(table_row);
})
});
</script>
</head>
<body>
<table id=""></table>
</body>
精彩评论