parthiban
parthiban

Reputation: 125

Datatable with static json data source

I am trying to create a datatable with static data in json format without getting the json source data by hitting the server through ajax request. Tried hard to find a way to do it, but no luck.Is it possible to do it with static json data variable as shown below,

<!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>

Please give example ways of doing this. Thanks in advance.

Upvotes: 3

Views: 16763

Answers (1)

Yuri
Yuri

Reputation: 3284

By including your JS code in $(function(){}), it will be run before your <table> is created. So you have to: 1. put that code right at the end of your <body>; 2. put in $(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

Upvotes: 15

Related Questions