【问题标题】:Datatable with static json data source具有静态 json 数据源的数据表
【发布时间】:2016-10-27 03:50:30
【问题描述】:

我正在尝试使用 json 格式的静态数据创建一个数据表,而无需通过 ajax 请求访问服务器来获取 json 源数据。 努力想办法做到这一点,但没有运气。是否可以使用静态json数据变量来做到这一点,如下所示,

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery DataTable</title>
  <link rel="stylesheet" href="jquery-ui.css">
  <link rel="stylesheet" type="text/css" href="demo_table_jui.css" />
  <link rel="stylesheet" type="text/css" href="jquery-ui-1.7.2.custom.css" />
  <script src="jquery-1.10.2.js"></script>
  <script src="jquery-ui.js"></script>
  <script type="text/javascript" src="complete.min.js"></script>
  <script type="text/javascript" src="jquery.dataTables.min.js"></script>


  <script>
  $(function() {
  var jsonData = [{"userID":"1","userName":"name1"},{"userID":"2","userName":"name2"},{"userID":"3","userName":"name3"}];
	$('#example').dataTable({
		data: jsonData,
		    columns: [
		        { data: 'userID' },
		        { data: 'userName' }
    		]
	});

  });
  </script>

</head>
<body>

<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" align="center">
	<thead>
		<tr>
			<th>UserID</th>
			<th>userName</th>
		</tr>
	</thead>
	<tbody>

	</tbody>
</table>

</body>
</html>

请举例说明这样做的方法。提前致谢。

【问题讨论】:

  • 您是否尝试删除 $function() 并替换为 $(document).ready(function() {
  • 你的代码其实是working
  • 也试过 $(document).ready() 。没用@john
  • 你能不能也让它为我工作? @尤里
  • @Anonymous 检查我答案中的链接。正如约翰建议的那样,将您的代码放入 $(document).ready...

标签: jquery json datatable


【解决方案1】:

通过在$(function(){}) 中包含您的JS 代码,它将在您的&lt;table&gt; 创建之前运行。所以你必须: 1. 将该代码放在&lt;body&gt; 的末尾; 2.输入$(document).ready();

$(document).ready(function(){
    var jsonData = [{"userID":"1","userName":"name1"},{"userID":"2","userName":"name2"},{"userID":"3","userName":"name3"}];
    $('#example').dataTable({
        data: jsonData,
        columns: [
            { data: 'userID' },
            { data: 'userName' }
        ]
    });
});

Working fiddle

【讨论】:

  • 文档中的完全相同的代码已准备好无法正常工作。有什么想法吗?
  • 这与正在使用的 jquery 或 datatable 的版本有关吗?
  • 你的控制台有错误吗?还可以尝试更新的 jQuery 版本
  • 通过用新版本替换 jquery 和 datatable 解决了这个问题。谢谢
猜你喜欢
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 2020-01-09
  • 2022-01-20
相关资源
最近更新 更多