简体   繁体   中英

how to render columns from `dataSrc` function in datatable?

i want to show data from API into datatable using AJAX Request, this is my API response:

{
    "title": "success",
    "data": {
        "name": "yogi",
        "email": "yogi@gmail.com",
        "activity": [
            {
                "name": "pergi"
            },
            {
                "name": "belanja"
            },
            {
                "name": "makan"
            },
            {
                "name": "tidur"
            }
        ]
    }
}

and this is my datatable script:

$(document).ready(function () {
    $("#activity-list").DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: `${baseurl}/api/user/${user_id}/activity`,
            dataSrc: function (json) {
                let results = [];
                for (let i = 0; i < json.data.activity.length; i++) {
                    results.push({
                        name: json.data.name,
                        email: json.data.email,
                        activity: json.data.activity[i].name,
                    });
                }
                return results;
            },
        },
    });
});

why the data doesn't appear, instead i got error message?

The only thing you are missing is the columns option, which maps your results array to the HTML table's columns:

$("#activity-list").DataTable({
  processing: true,
  serverSide: true,
  columns: [
    { data: "name" },
    { data: "email" },
    { data: "activity" }
  ],
  ajax: {
    url: '[my test URL here]',
    dataSrc: function (json) {
      let results = [];
      for (let i = 0; i < json.data.activity.length; i++) {
        results.push({
          name: json.data.name,
          email: json.data.email,
          activity: json.data.activity[i].name,
        });
      }
      return results;
    }
  }
});

This assumes you have a HTML table defined which already has the column headers you want to display:

<table id="activity-list" class="display dataTable cell-border" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Activity</th>
        </tr>
    </thead>
</table>

(Or, you could add those headings to the DataTables columns option using title , if you prefer.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM