Advertisement
mzografski

JSAPPSHW1.3

Nov 20th, 2014
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function parseText(str) {
  2.         try{
  3.             var resObj = jQuery.parseJSON(str);        
  4.             generateTable(resObj);
  5.         }catch(e){         
  6.             if(e instanceof SyntaxError) {
  7.                  alert("There was a syntax error in your JSON string.\n" + e.message + "\nPlease check your syntax and try again.");
  8.                  jQuery("jsonText").focus();
  9.                  return;
  10.             }
  11.  
  12.             alert("There was an unknown error. Perhaps the JSON string contained a deep level of nesting.");
  13.             jQuery("jsonText").focus();
  14.             return;
  15.         }
  16.     }
  17.    
  18.     function generateTable (obj) {
  19.         var table, tbody, theader, tr, td, th, rowB, rowH;
  20.         table = jQuery('<table class="table"><thead></thead><tbody></tbody></table>');
  21.         thead = table.children('thead');       
  22.         tbody = table.children('tbody');
  23.         tr = '<tr></tr>';
  24.         th = '<th></th>';
  25.         td = '<td></td>';
  26.  
  27.         $.each(obj, function (ind, sub) {              
  28.             if(typeof sub === 'object'){
  29.                 if(ind === 0){
  30.                     rowH = $(tr);
  31.                 }
  32.                 rowB = $(tr);              
  33.                 $.each(sub, function (key, val) {
  34.                     if(ind === 0){
  35.                         rowH.append($(th).text(key));
  36.                     }
  37.                     rowB.append($(td).text(val))
  38.                 });
  39.                 rowB.appendTo(tbody);
  40.             }
  41.         });
  42.         rowH.appendTo(thead);
  43.         $('#main').append(table);
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement