如何将JavaScript数据传递给jQuery DataTables

时间:2015-07-20 03:02:56

标签: javascript jquery datatables

我非常沮丧地尝试在表格中插入和显示JSON。我正在使用jQuery DataTable来实现它。

我有以下jQuery和HTML代码,但没有成功:

<table id="sectorsTable">
    <thead>
        <tr>
            <th><b>Numero</b></th>
            <th><b>Nombre</b></th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<script>
var jsonArray = { layersSelected: temporaryArraySectors };
var jsonString = JSON.stringify(jsonArray, null, 2);

$('#sectorsTable').dataTable({ 
    'ajax': jsonString
});
</script>

顺便说一下,变量的内容是:

temporaryArraySectors = [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ];
jsonString = '{"layersSelected": [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ] }';

有什么问题?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您不需要使用JSON.stringify创建JSON字符串,只需将data选项设置为temporaryArraySectors

请参阅下面的示例以获取代码和演示。

&#13;
&#13;
$(document).ready(function() {

  var temporaryArraySectors = [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ];
  
  var table = $('#sectorsTable').DataTable({
    data: temporaryArraySectors 
  });

});
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="ISO-8859-1">

  <link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
  <script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>

</head>

<body>
  <table id="sectorsTable" class="display">
     <thead>
         <tr>
             <th><b>Numero</b></th>
             <th><b>Nombre</b></th>
         </tr>
     </thead>
     <tbody>
     </tbody>
  </table>
</body>

</html>
&#13;
&#13;
&#13;