java 如何使用从 Spring MVC 发回的 JSON 对象填充 jQuery 数据表的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12841510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:26:07  来源:igfitidea点击:

How to populate rows of jQuery datatable with JSON object sent back from Spring MVC?

javajqueryjsonspring-mvcdatatables

提问by IAmYourFaja

I have a Java(Spring MVC) backend that returns POJOsas JSONobjects as follows:

我有一个Java(Spring MVC) 后端,它将POJO作为JSON对象返回,如下所示:

@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 /getWidgetsByTypefrom inside a jQuery$.getJSONcall, and then use the JSONresults 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:

在前端,我试图调用/getWidgetsByType从内jQuery的$.getJSON呼叫,然后使用JSON结果来从后面来填充数据表。具体来说,我希望数据表出现<div>在页面加载时当前为空的标签内,如下所示:

<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 datatableto contain the same columnsas the fieldsof the WidgetVO(type, name, isAwesome), all as Stringvalues (no renderers, etc.).

我想datatable包含相同的中的WidgetVO(类型,名称,isAwesome),所有的String值(不渲染器等)。

Thanks in advance for any help here!

在此先感谢您的帮助!

采纳答案by bhb

Examplefrom the datatable site gives you all the details required.

来自数据表站点的示例为您提供了所需的所有详细信息。

Example JS code

示例 JS 代码

$(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

你的 json 应该是这样的

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

Here'sexample showing to set the column names on the fly.

这是显示动态设置列名称示例。

Cheers!!

干杯!!

回答by surya handoko

1.Controller

1.控制器

@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

2.道

 @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

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

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

希望这有帮助

回答by Kamiel Ahmadpour

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:

从 Spring 获取适当的 JSON 数据到 DataTable 的最简单方法是返回一个像这样的映射而不是返回实体列表:

    @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" }

    ]
});

});

});