Present JSON data to a play framework template

痴心易碎 提交于 2019-12-24 10:48:15

问题


Trying to get it to work without any detail knowledge of JQuery. I am really having a hard time finding an comprehensible example of how i would create an unnumbered list out of some json that i am passing to the front inside a String object.

I am using the Play! Framework. My Application has a method that returns a string holding an json array of items.

GET     /items                       controllers.Application.items()

the method looks like this:

public static Result items() {      
    return ok(Json.toJson(Item.all()));
}

How would you process this data in order to have your template present it as an unnumbered list?

the data, example:

@Entity
public class Item {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public String title;

public String type;
public int quantity;
public BigDecimal unitPrice;

public Item() {}

public static List<Item> all() {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    TypedQuery<Item> query = entityManager.createQuery("SELECT i FROM Item i", Item.class);
    return query.getResultList();
}

回答1:


You need to call the items() action with a javascript ajax request. Then you can use javascript and jQuery to create your list.

something like this:

<script type="text/javascript">
    $(function(){
        $.getJSON('/items', function(items){
            var ul = $('<ul>');
            $.each(items, function(item){
                var li = $('<li>').text(item.title);
                ul.append(li);
            });

            $('body').append(ul);
        });
    });    
</script>


来源:https://stackoverflow.com/questions/11352310/present-json-data-to-a-play-framework-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!