How to display JSON data in jQuery DataTables via Ajax?

I am trying to get JSON data in a jQuery DataTables component.

First I wrote JavaScript and a view similar to the one below:

$.fn.dataTable.Editor({
    ajax: "http://localhost/example22/index.php?r=site/display",
    table: "#example",
    fields: [{
        label: "Name:",
        name: "name"
    }, {
        label: "Designation:",
        name: "designation"
    }, {
        label: "Address:",
        name: "address"
    }, {
        label: "Salary:",
        name: "salary"
    }]
});

$('#example').DataTable({
    lengthChange: false,
    ajax: "http://localhost/example22/index.php?r=site/display",
    columns: [{
        allk: "name"
    }, {
        allk: "designation"
    }, {
        allk: "address"
    }, {
        allk: "salary"
    }],
    select: true
});

and kind like

<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Address</th>
                <th>Salary</th>
            </tr>
        </thead>
</table>

and the provided URL contains the following JSON data, respectively

{
    "allk": [
        {
            "name": "raju",
            "designation": "developer",
            "address": "he is from viswasapuram",
            "salary": "30000"
        },
        {
            "name": "bob",
            "designation": "designer",
            "address": "no idea",
            "salary": "100000"
        },
        {
            "name": "bob",
            "designation": "designer",
            "address": "no idea",
            "salary": "100000"
        },
        {
            "name": "suresh",
            "designation": "designer",
            "address": "fffswss",
            "salary": "1212"
        },
        {
            "name": "john",
            "designation": "designer",
            "address": "california",
            "salary": "3000000"
        },
        {
            "name": "suresh",
            "designation": "tester",
            "address": "he is from cheeran maanagar",
            "salary": "20000"
        }
    ]
}

Can someone help me on how to use DataTables with this application?

+4
source share
1 answer

DECISION

Use the parameter ajax.dataSrcto specify property storage data in the JSON response.

For example:

$('#example').DataTable({
   // ... skipped other options ...
   ajax: {
       url: "http://localhost/example22/index.php?r=site/display",
       dataSrc: 'allk'
   },
   columns: [
       { data: "name"}, 
       { data: "designation"}, 
       { data: "address" }, 
       { data: "salary"}
   ]
});

Demo

See this jsFiddle for code and demos.

+3
source

Source: https://habr.com/ru/post/1607026/


All Articles