传递动态json数据以填充jquery网格

时间:2013-07-15 12:03:36

标签: jquery json

我必须使用未定义的列创建一个基于Json数据的网格

[{
    Name: "John",
    Designation: "Analyst",
    Age: 25, 
    Department: "IT"
},
{
    Name: "Matthew",
    Designation: "Manager", 
    Age: 38, 
    Department: "Accounts"
},
{
    Name: "Emma",
    Designation: "Senior Manager",
    Age: 40,
    Department: "HR"
}];

我想要的输出如下:

标题:

Name | Designation | Age | Department

as datarow:

John | Analyst | 25 | IT

请有人帮助我如何开始以及如何做。

4 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

$.each(Jsonstring,function(){
  alert(JsonString.Name);
  alert(JsonString.Designation)
  alert(JsonString.Age)
  alert(JsonString.Department)
});

答案 2 :(得分:0)

这里我已经迭代并以表格格式显示数据这是您正在寻找的Fiddle Demo

$table = "<table id = 'resultTable' border=1>";
$.each(data[0] , function(key, value){
   $table += "<td>"+key+"</td>";
});
$table += "<tr>";

for (var i = 0; i < data.length; i++) {

    $table += "<tr>";

    var it = data[i];



    $table += "<td>" + data[i].Name + "</td>";

    $table += "<td>" + data[i].Designation + "</td>";

    $table += "<td>" + data[i].Age + "</td>";

    $table += "<td>" + data[i].Department + "</td>";

    //alert(items[i].duration);
    $table += "</tr>";

}

$table += "</table>";

$('body').append($table);

答案 3 :(得分:0)

for ... in循环将完全按照您的需要进行操作。

以下是Mozilla开发者网络撰写的内容: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

在“for ... in循环”中,测试属性是否具有指定的属性并且不继承此属性至关重要。(hasOwnProperty

工作示例:http://jsbin.com/ecoqax/1/edit

我在这里使用jQuery:

var $theader = $("thead"),
    $tbody = $("tbody"),
    hasHeader = false,
    html = "";

  // data is the converted JSON data
  for (var i = 0; i < data.length; i++) {
    // the current person
    var person = data[i];

    html += '<tr>';

    // iterating over every property of the person object
    for (var prop in person) {
      if (person.hasOwnProperty(prop)) {
        // insert the header once
        if (hasHeader === false) {
          $theader.append($('<th>'+prop+'</th>'));
        }
        html += '<td>'+person[prop]+'</td>';
      }
    }

    // after the first iteration the header is added
    hasHeader = true;
    html += '</tr>';
  }

  $tbody.append($(html));