2013-12-09 12 views

risposta

11

semplice con jQuery:

$(function(){ 

     var jsonObj = $.parseJSON('{"a":1,"b":3,"ds":4}'); 
     var html = '<table border="1">'; 
     $.each(jsonObj, function(key, value){ 
      html += '<tr>'; 
      html += '<td>' + key + '</td>'; 
      html += '<td>' + value + '</td>'; 
      html += '</tr>'; 
     }); 
     html += '</table>'; 

     $('div').html(html); 
    }); 

prova: http://jsfiddle.net/T7eQg/1/

EDIT

ed è possibile utilizzare questo js libreria. Questa libreria convertito JSON a tavola con ordinamento e ecc: http://www.dynatable.com/

+0

Il codice è un molto più semplice del codice che avevo e molto più pulito. Grazie ... mi hai salvato l'anima! – BeemerGuy

0

Si dovrebbe dare un'occhiata a knockout.js. Con questo, puoi prendere i tuoi dati (Json) e collegarli agli elementi HTML. L'aggiornamento, ecc., Viene quindi eseguito automaticamente, quindi non devi scherzare da solo. Dai un'occhiata agli esempi: http://knockoutjs.com/examples/simpleList.html

5

È possibile utilizzare javascript:

<script type="text-javascript"> 
    var data = {"a": 1, "b": 3, "ds": 4};  

    // Create a new table 
    var table = document.createElement("table"); 

    // Add the table header 
    var tr = document.createElement('tr'); 
    var leftRow = document.createElement('td'); 
    leftRow.innerHTML = "Name"; 
    tr.appendChild(leftRow); 
    var rightRow = document.createElement('td'); 
    rightRow.innerHTML = "Value"; 
    tr.appendChild(rightRow); 
    table.appendChild(tr); 

    // Add the table rows 
    for (var name in data) { 
     var value = data[name]; 
     var tr = document.createElement('tr'); 
     var leftRow = document.createElement('td'); 
     leftRow.innerHTML = name; 
     tr.appendChild(leftRow); 
     var rightRow = document.createElement('td'); 
     rightRow.innerHTML = value; 
     tr.appendChild(rightRow); 
     table.appendChild(tr); 
    } 

    // Add the created table to the HTML page 
    document.body.appendChild(table); 
</script> 

jsfiddle

La struttura HTML risultante è:

<table> 
    <tr> 
     <td>Name</td> 
     <td>Value</td> 
    </tr> 
    <tr> 
     <td>a</td> 
     <td>1</td> 
    </tr> 
    <tr> 
     <td>b</td> 
     <td>3</td> 
    </tr> 
    <tr> 
     <td>ds</td> 
     <td>4</td> 
    </tr> 
</table> 
Problemi correlati