gpt4 book ai didi

javascript - Play Framework : Display data as html table

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:34 27 4
gpt4 key购买 nike

我正在开发一个有几个表的小项目。其中之一是 Person 表,它具有 id 和 name 作为属性。我成功地从数据库中获取了结果集(使用 MySql)并且可以将它们转换成 json。但是,我找不到将 json 显示为 html 表的方法。有没有办法将人员列表传递给 html 并将其显示在表格中??

应用程序.java

public class Application extends Controller {

@Inject
FormFactory formFactory;

public Result index() {
return ok(index.render());
}

@Transactional(readOnly = true)
public Result getPersons() {
List<Person> persons = (List<Person>) JPA.em().createQuery("select p from Person p").getResultList();
return ok(toJson(persons));
}

index.scala.html

 @()
@main("Welcome to Play") {
<script type='text/javascript' src='@routes.Assets.at("javascripts/index.js")'></script>

<ul id="persons"></ul>

//logic to display table
}

index.coffee

$ ->
$.get "/persons", (persons) ->
$.each persons, (index, person) ->
$("#persons").append $("<li>").text person.id + person.name

这会显示人物对象列表。但我需要显示一个 html 表格

最佳答案

However, i am unable to find a way to display the json as a html table. Is there a way to pass the list of Persons to the html and just display it in a table ??

看来您没有很好地阅读 Play 手册。但是,我不会将 JSON 发送到模板。相反,我会通过

List<Persons> 

(Java Object) 到 scala 模板并使用 Scala 模板语言来显示表格。我认为您会从阅读模板帮助页面中受益 here.

要特别注意执行 for 循环的迭代部分。这就是我的做法(未经测试):

index.scala.html

@(persons: List[Person])
@main("Welcome to Play") {
<script type='text/javascript' src='@routes.Assets.at("javascripts/index.js")'></script>

<ul id="persons"></ul>

//logic to display table
<table>
@for(person <- persons){
<tr>
<td>@person.getName()</td>
<td>@person.getId()</td>
</tr>
}
</table>
}

请注意,在 Scala 模板中,不要使用以下语法:

List<Person>

(就像在 Java 中一样),你使用

List[Person]  

对于应用程序 Controller ,将相关部分更改为:

public Result getPersons() {
List<Person> persons = (List<Person>) JPA.em().createQuery("select p from Person p").getResultList();
return ok(index.render(persons);

假设您在 Person 类中有两个字段:name 和 id。它还假设您有它们的“获取”方法。如果它们是公共(public)字段,您可以使用@person.name 和@person.id。更改这些变量以匹配您在 Person 类中的内容。

那么你不应该需要 index.coffee。您也不需要 index.scala.html 中的标签(除非您出于其他原因需要它)。

在上述帮助页面上,您还可以查看“声明可重用 block ”部分以创建可重用 block 来显示每个 Person 对象。但是,我会先让最简单的版本运行,然后再尝试。

关于javascript - Play Framework : Display data as html table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com