2015-02-08 105 views
0

我列的一个阵列:从JSON数据动态检索列

var columns=["title","length","status"]; 

这里是我的代码:

function executeSearch(query) 
    {      
     var url = ajaxPath+ "?s=search&r="+resource+"&q="+query; 
     $.getJSON(url, function(data){   
      var html = '<table class="table table-hover">'; 
      html += '<thead><tr>'; 
      $(columns).each(function(index,value){ 
       html +='<td>'+value+'</td>'; 
      }) 
      html += '</tr></thead>'; 
      html += '<tbody>';   
      $(data).each(function(i,item){ 
       html += '<tr>'; 
       $(item).each(function(e,itm){ 
        for(var propt in itm){ 
         if (columns.hasOwnProperty(propt)) { 
          html += '<td>'+itm[propt]+'</td>'; 
         } 
        }     
       }) 
       html += '</tr>'; 
      }); 
      html += '</tbody>'; 
      html += '</table>'; 
      $("#datatable").html(html); 
     }); 
    } 

我试图得到一个基于列中的数据。我正在使用columns.hasOwnProperty

它似乎没有正常工作。

是否有jquery方法来处理?

回答

0

columns在你的例子中是一个数组,你应该使用indexOf来判断列是否在数组中。

// check if the propt is in the array (-1 means not found) 
if (coulmns.indexOf(propt) !== -1) { 

然而,在情况下,你都在看着你大概应该是在columns阵列,而不是items财产迭代。你需要建立一个表,你想要的列将在您指定的顺序...

相反的$(item).each()你应该$.each(columns, function(index, propt) {使用item[propt]

+0

感谢您的建表。这工作,但我想我需要遍历每个tr项目,并将列应用于每个td。无论如何,它运行良好。谢谢 – jkushner 2015-02-08 16:13:22