Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load the local JSON variable using jquery datatable

I have a local JSON dataset. I want to use jquery datatable plugin to display it. Is there any setting or configuration inside datatable plugin to display data? All I can find is to make AJAX calls and server calls.

Thanks for the help.

like image 719
prgrmr Avatar asked Oct 03 '11 20:10

prgrmr


2 Answers

You can supply DataTables with data 4 different ways

  • DOM
  • Javascript array
  • Ajax source
  • Server side processing

In your situation, you will want to use the second (Javascript Array) option. You will need to be able to translate the shape of your JSON object into an array objects.

Here's an example

var json = {
  BrowserStats : [
    { engine: "Trident", browser: "IE 4.0", platform: "Win 95+", version: 4 },
    { engine: "Trident", browser: "IE 5.0", platform: "Win 95+", version: 5 },
    { engine: "Trident", browser: "IE 5.5", platform: "Win 95+", version: 5.5 }
  ]
};

var data = jQuery.map(json.BrowserStats, function(el, i) {
  return new [el.engine, el.browser, el.platform, el.version];
});

$('#example').dataTable( {
  "aaData": data,
  "aoColumns": [
    { "sTitle": "Engine" },
    { "sTitle": "Browser" },
    { "sTitle": "Platform" },
    { "sTitle": "Version"}
  ]
});
like image 76
jessegavin Avatar answered Sep 17 '22 17:09

jessegavin


You can get your json local file doing a normal ajax call, with some caveats (see http://en.wikipedia.org/wiki/Same_origin_policy, or jQuery's .getJSON using local files stopped working on Firefox 3.6.13, fwiw)

But it should definitely be possible to do:

$.getJSON('page.json', function(data) {
    /* do something with each item in data */
});
like image 41
Savino Sguera Avatar answered Sep 17 '22 17:09

Savino Sguera