2015-02-08 74 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