Using JSON object to create datatable

Using JSON object to create datatable

gron2gron2 Posts: 5Questions: 2Answers: 0

I tried use datatable in js in asp.net. One example I followed is https://www.datatables.net/examples/ajax/objects_subarrays.html

My json data is more simple than it gave but the structure is similar

{
    "data":
    {
      "name":"Nixon",
      "hr": "System Architect",
      "office": "Edinburgh",
      "extn": "5421"
    }
}

But anyway in JavaScript it wrote is "ajax":"data/object_subarrays.txt", but in my case, I got a json object "msg" in javascript.

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": "data/objects_subarrays.txt",
        "columns": [
            { "data": "name[, ]" },
            { "data": "hr.0" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "hr.2" },
            { "data": "hr.1" }
        ]
    } );
} );

How can I create the datatable via JSON object insteady of using .txt or php page?
Cheers.

Answers

  • allanallan Posts: 61,746Questions: 1Answers: 10,111 Site admin

    I'm afraid I don't really understand the question. Are you asking how you can load data from something other than a txt file? Just change the ajax source string.

    If you want to load data into the table in Javascript (i.e. not via Ajax) thenn use data.

    Allan

  • gron2gron2 Posts: 5Questions: 2Answers: 0

    Hi Allan, I got the data from database via ajax. So I could not write down all data in javascript, I want to create a datatable in javascript and put data into the datatable via using a json object in javascript. Now I just have a json object/variable called "msg" which includes all data in javascript now. The format is above.

    If I want to create a datatable via using this json object. How do I write?

    It looks like I should use the below example but I wonder in "url", the "data.json" word, the "data" is the json object name or the below xx in the data

    {"xx":[{"id:"1""}]}
    

    . That means should I write "url":"msg.json" or "url":"xx.json"

    Add data to the request by manipulating the data object:

    $('#example').dataTable( {
      "ajax": {
        "url": "data.json",
        "data": function ( d ) {
            d.extra_search = $('#extra').val();
        }
      }
    } );
    

    And what is #extra?
    Do I use the correct example?

    Cheers

  • allanallan Posts: 61,746Questions: 1Answers: 10,111 Site admin

    If I want to create a datatable via using this json object. How do I write?

    $('#myTable').DataTable( myOptions );
    

    Allan

  • gron2gron2 Posts: 5Questions: 2Answers: 0

    Hi Allan,
    {"xx":[{"id":"1"}]}
    Forgive my fool, that "myOptions" is the name of the json object or write a loop to insert the json data into the datatable?

    I tried the $('#myTable').DataTable(msg); and $('#myTable').DataTable(msg.xx); Both of them cannot work.
    Cheers.

This discussion has been closed.