javascript 如何在 Thymeleaf 中将 JSON 值从 Controller 传递到 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29247523/
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-28 10:16:54  来源:igfitidea点击:

How to pass JSON value from Controller to HTML in Thymeleaf?

javascriptjqueryjsonspring-mvcthymeleaf

提问by Ke Vin

I try do do "Server side pagination" using DataTables. I was following this tutorial to get it done "http://javahonk.com/spring-mvc-pagination-datatables/". It's using JSP as their html language. What i using here is "Thymeleaf"

我尝试使用 DataTables 做“服务器端分页”。我正在按照本教程完成“ http://javahonk.com/spring-mvc-pagination-datatables/”。它使用 JSP 作为他们的 html 语言。我在这里使用的是“Thymeleaf”

but when i trying to do that, i stuck at the JSON value is already generated, but it appear in my console and won't show up in my HTML page

但是当我尝试这样做时,我停留在 JSON 值已经生成,但它出现在我的控制台中并且不会出现在我的 HTML 页面中

Here is my controller : SpringMVCController.java

这是我的控制器:SpringMVCController.java

@RequestMapping(value = "/barangs", method = RequestMethod.GET, produces = "application/json")
public String processFindBarang(HttpServletRequest request) {

//Fetch the page number from client
Integer pageNumber = 0;
if (null != request.getParameter("iDisplayStart"))
    pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/10)+1;     

//Fetch search parameter
String searchParameter = request.getParameter("sSearch");

//Fetch Page display length
Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength"));

//Create page list data
Collection<ReturOrder> returList = createPaginationData(pageDisplayLength);

ReturObjectJson returJsonObject = new ReturObjectJson();
//Set Total display record
returJsonObject.setiTotalDisplayRecords(200);
//Set Total record
returJsonObject.setiTotalRecords(200);
returJsonObject.setAaData(returList);

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(returJsonObject);

return json2;

}

}

it's already return the JSON nicely done, it appear in my "console" area while debuging in my Eclipse IDE

它已经很好地返回了 JSON,它在我的 Eclipse IDE 中调试时出现在我的“控制台”区域中

Here is my HTML page. Main.html

这是我的 HTML 页面。主文件

<form method="GET">
<h2>Spring MVC pagination using data tables</h2>
<table width="70%" style="border: 3px;background: rgb(243, 244, 248);"><tr><td>
<table id="tablepage" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Nomor_Transaksi</th>
                <th>Tgl_Trans</th>
                <th>FlagCetak</th>
                <th>Kd_Plg</th>
            </tr>
        </thead>   
    </table>
    </td></tr></table>
</form>

And here is my javascript at area

这是我在区域的 javascript

<script type="text/javascript" th:inline="javascript">

    //Plug-in to fetch page data
jQuery.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart":         oSettings._iDisplayStart,
"iEnd":           oSettings.fnDisplayEnd(),
"iLength":        oSettings._iDisplayLength,
"iTotal":         oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage":          oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages":    oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};

$(document).ready(function() {

$("#tablepage").dataTable( {
        "bProcessing": true,
        "bServerSide": true,
        "sort": "position",
        //bStateSave variable you can use to save state on client cookies: set value "true"
        "bStateSave": false,
        //Default: Page display length
        "iDisplayLength": 10,
        //We will use below variable to track page number on server side(For more information visit: http://legacy.datatables.net/usage/options#iDisplayStart)
        "iDisplayStart": 0,
        "fnDrawCallback": function () {
            //Get page numer on client. Please note: number start from 0 So
            //for the first page you will see 0 second page 1 third page 2...
            //Un-comment below alert to see page number
         //alert("Current page number: "+this.fnPagingInfo().iPage);    
        },        
        "sAjaxSource": "barangs",
        "aoColumns": [
            { "mData": "Nomor_Transaksi" },
            { "mData": "Tgl_Trans" },
            { "mData": "FlagCetak" },
            { "mData": "Kd_Plg" },

        ]
    } );

} );

</script>

the value won't show up, it give me these error while executing in my web browser. it show up a alert box that said : "DataTables warning: table id=tablepage - Ajax error. For more information about this error, please see http://datatables.net/tn/7"

该值不会显示,它在我的 Web 浏览器中执行时给我这些错误。它显示一个警告框,上面写着:“ DataTables 警告:table id=tablepage - Ajax 错误。有关此错误的更多信息,请参阅http://datatables.net/tn/7

but when i look into my eclipse console, the JSON value suchs as :

但是当我查看我的 Eclipse 控制台时,JSON 值例如:

    {
      "Nomor_Transaksi": "xxxxx",
      "Tgl_Trans": "Jan 15, 2014 12:00:00 AM",
      "FlagCetak": "Y",
      "Kd_Plg": "MGS                    "
    },
    {
      "Nomor_Transaksi": "xxxxx",
      "Tgl_Trans": "Jan 6, 2014 12:00:00 AM",
      "FlagCetak": "Y",
      "Kd_Plg": "MGS                    "
    }
  ]
}", template might not exist or might not be accessible by any of the configured Template Resolvers

whan i am missed here?

我在这里想念吗?

回答by Ke Vin

Found it! i missed a @ResponseBody tag!

找到了!我错过了@ResponseBody 标签!

so here is my Controller function

所以这是我的控制器功能

@RequestMapping(value = "/barangs", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody String processFindBarang(HttpServletRequest request) {

//Fetch Page display length
Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength"));

//Fetch the page number from client
Integer pageNumber = 0;
if (null != request.getParameter("iDisplayStart"))
    pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/pageDisplayLength)+1;      

/*  //Fetch search parameter
    String searchParameter = request.getParameter("sSearch");*/

//Create page list data
List<ReturOrder> returList = createPaginationData(pageDisplayLength, pageNumber);

ReturObjectJson returJsonObject = new ReturObjectJson();
//Set Total display record
returJsonObject.setiTotalDisplayRecords(200);
//Set Total record
returJsonObject.setiTotalRecords(200);
returJsonObject.setAaData(returList);

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(returJsonObject);

return json2;
}