How to display the column headers dynamically in jquery data table

后端 未结 2 2062
别那么骄傲
别那么骄傲 2021-01-06 06:14

I have the below code for displaying array of objects having property and a value in a data table. But here the column headers are hardcoded as seen in my below html code. H

2条回答
  •  猫巷女王i
    2021-01-06 06:49

    Here is the answer to fetch it from external json

    HTML

    
      
    
    
    

    script.js

    jQuery( document ).ready( function( $ ) {
            // Code using $ as usual goes here.
    
            $.ajax( {
                url: '1.json',
                dataType: "json",
                "success": function ( json ) {
                  var tables = $("#example").DataTable({               
                    dom : 'l<"#add">frtip',
                    "language": {
        "paginate": {
          "previous": "< Previous",
          "next": "next >"
        }
      },
                    "columnDefs": [ {
        "targets": 2,
        "createdCell": function (td, cellData, rowData, row, col) {
          if (( cellData > 3 ) && ( cellData < 30 )){
            $(td).css('color', 'green')
          }
          else
               if (( cellData > 31 ) && ( cellData < 50 )){
            $(td).css('color', 'orange')
          }
          else
               if (( cellData > 51 ) && ( cellData < 100 )){
            $(td).css('color', 'red')
          }
        }
      } ],
                    "ajax": {
                        "url": "1.json",
                        "type": "POST",
                        "datatype": "json"
                    },
                    "columns": json.columns
                });
                $('