2023-01-12

Finding - 2 different ways to get result from API to showing by using Datatables.net

 


Reference URL: https://stackoverflow.com/a/68456824/6462295

As of 2023Feb07_1503 - failed to achieve by method of: data: data

Published on
1/12/23 2:25 PM






My html table:

<table id="listaVideos2" class="display">
        <thead>
        <tr>
            <th>nombre</th>
            <th>descripcion</th>
            <th>codigoYoutube</th>
            <th>bpm</th>
        </tr>
        </thead>
    </table>

My JavaScript:

$.ajax({
        "url": "listado2",
        "type": "GET",
        "datatype": 'json',
        "success": function (data) {
            $('#listaVideos2').DataTable({
                "fixedHeader" : true,
                "paging":   false,
                "info":     true,
                "autoWidth": true,
                "order": [],
                data: data,
                select: true,
                columns: [
                    { "data": "nombre" },
                    { "data": "descripcion" },
                    { "data": "codigoYoutube",
                        "title": "Youtube",
                        "orderable": false
                    },
                    { "data": "bpm" },
                ]
            });
        }
    });

or another way you can use:

$('#listaVideos2').DataTable({
        "fixedHeader" : true,
        "paging":   false,
        "info":     true,
        "autoWidth": true,
        "order": [],
        ajax: {
            url: 'listado2',
            dataSrc: ''
        },
        select: true,
        columns: [
            { "data": "nombre" },
            { "data": "descripcion" },
            { "data": "codigoYoutube",
                "title": "Youtube",
                "orderable": false
            },
            { "data": "bpm" },
        ],
        buttons: [
            { extend: "create", editor: editor },
            { extend: "edit",   editor: editor },
            { extend: "remove", editor: editor }
        ],
        dom: "Bfrtip",
    });

And my Controller: (if your controller is a @RestController I think you wouldn't need the @ResponseBody)

@GetMapping("/listado2")
    @ResponseBody
    public List<Video> apiListadoVideos() {
        return videosServicio.buscarTodosLosVideos();
    }

where my Video class is this simple (I just remove de getters, setters...):

public class Video {
    private Integer id;
    @NotEmpty
    @NotBlank
    private String nombre;
    private String descripcion;
    @NonNull @NotBlank
    private String codigoYoutube;
    private String bpm;
    private Categoria categoria;
    private Tono tono;
    private Modo modo;
}















No comments:

Post a Comment