How to populate rows of jQuery datatable with JSON

2019-03-31 19:26发布

问题:

I have a Java (Spring MVC) backend that returns POJOs as JSON objects as follows:

@RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST)
public @ResponseBody List<WidgetVO> getWidgetsByType(@RequestParam("type") String type)
{
    return widgetDAO.getWidgetsByType(token);
}   

public class WidgetVO {
    private String type;
    private String name;
    private boolean isAwesome;

    // Getters and setters, etc.
}

In the frontend I'm trying to call /getWidgetsByType from inside a jQuery $.getJSON call, and then use the JSON results coming back from that to populate a datatable. Specifically, I want the datatable to appear inside a <div> tag that is currently empty at page load as follows:

<div id="#table-to-display"></div>

var t = getTypeFromDOM();

$.getJSON(
    url: "/getWidgetsByType",
    data: {
        type: t
    },
    success: function() {
        // How do I extract the JSON version of the List<WidgetVO>'s coming
        // back from the server and use them to populate the table?
        $("#table-to-display").datatable();
    }
);

I would like the datatable to contain the same columns as the fields of the WidgetVO (type, name, isAwesome), all as String values (no renderers, etc.).

Thanks in advance for any help here!

回答1:

Example from the datatable site gives you all the details required.

Example JS code

$(document).ready(function() {
  $('#example').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "scripts/server_processing.php" // for you it will be - /getWidgetsByType
  } );
} );

Your json should be something like this

{
  "sEcho": 1,
  "iTotalRecords": "57",
  "iTotalDisplayRecords": "57",
  "aaData": [
    [],[],[],...
  ]
}

Here's example showing to set the column names on the fly.

Cheers!!



回答2:

1.Controller

@RequestMapping(value = "/json", method = RequestMethod.GET)
public
@ResponseBody
String listUsersJson(ModelMap model) throws JSONException {
    int no=1;
    JSONArray userArray = new JSONArray();
    for (TileType tT: tD.getAll()){   
        String n=Integer.toString(no);
        String id=Integer.toString(tT.getTileTypeId());          
        String[] value =
        {n,
         tT.getTileTypeName(),
         tT.getTileTypeDensity()         
        };   
        userArray.put(value);
        no++;
    }
    String x=userArray.toString();
    String replace1=x.replace("{", "[");
    String replace2=replace1.replace("}","]");
    String replace3=replace2.replace(":",",");
   return ("{\"aaData\":"+replace3+"}");        
}

2.Dao

 @Override
public List<TileType> getAll() {
    Session session=HibernateUtil.getSessionFactory().openSession();
    List<TileType>list=new ArrayList<TileType>();
    try{
    Query query=session.createQuery("from TileType T order by T.tileTypeId DESC");
    list=query.list();
    }
    catch(HibernateException he){}
return list;
   }

3.Javascript

var table = $('#example').dataTable({
     "sPaginationType": "full_numbers",
    "sAjaxSource": "/data/tipeTile/json",
    "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sLengthMenu": "_MENU_ records per page",
        "sSearch": ""
    }
         }); 

4.Html

  <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
                            <thead>
                                <tr>
                                    <th style="width: 50px">No</th>
                                    <th>Name</th>
                                    <th>Density</th>

                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>

Hope this Help



回答3:

The easiest way to get the appropriate JSON data from Spring to DataTable is that instead of returning a list of your entity, return a map like this:

    @RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST)
public @ResponseBody Map<String, WidgetVO> getWidgetsByType(@RequestParam("type") String type) {
    Map<String, WidgetVO> result = new HashMap<>();
    result.put("WidgetVO", widgetDAO.getWidgetsByType(token));
    return result;
}

That's it and now you can have access to your objects:

 $(document).ready(function() {
$('#example').dataTable( {
    "ajax": "data/objects.txt",
    "dataSrc": "WidgetVO",
    "columns": [
        { "data": "type" },
        { "data": "name" },
        { "data": "isAwesome" }

    ]
});

});