简体   繁体   English

如何从jsp访问列表到Javascript

[英]How to access a List from the jsp to Javascript

I am trying to transfer a list passed from the Controller (to the jsp), and pass the said list from the jsp to javascript. 我正在尝试将从Controller传递的列表(传递给jsp),并将所述列表从jsp传递给javascript。

The data on the list should replace the values of X (the date) and Y. 列表中的数据应替换X(日期)和Y的值。

var data = {
    values:[
        { X: "8/7/12",  Y: 21 },
        { X: "8/8/12",  Y: 32 },
        { X: "8/9/12",  Y: 62 },
        { X: "8/10/12", Y: 8  },
        { X: "8/11/12", Y: 40 },
        { X: "8/12/12", Y: 12 },
        { X: "8/13/12", Y: 14 },
        { X: "8/14/12", Y: 72 },
        { X: "8/15/12", Y: 11 },
        { X: "8/16/12", Y: 98 },
    ]};



The list I wish to pass contains the following: 我希望通过的列表包含以下内容:
1. the String version of LocalDate (Jodatime) - for the X axis 1. LocalDate的字符串版本(Jodatime)-用于X轴
2. the scores - for the y-axis 2.分数-y轴

I have seen and tried a couple of solutions based on situations in various forums online, but none of them worked the way it was intended to. 我已经在各种在线论坛上根据情况查看并尝试了几种解决方案,但是没有一种能够按预期的方式工作。 I also tried passing parallel arrays but none of them seemed to work. 我也尝试传递并行数组,但是它们似乎都不起作用。

You can simply do this from JSP to Javascript 您可以简单地从JSPJavascript执行此操作

var data = { values:[
        { X: <%=x[0]%>, Y: <%=y[0]%> },
        { X: <%=x[1]%>, Y: <%=y[1]%> },
        ...
    ]};

Note here I have use array of X and Y for values, you can use any data structure into jsp and later get it into javascript. 请注意,这里我使用X和Y数组作为值,您可以将任何数据结构用于jsp,然后将其放入javascript。

Alternatively If you are passing the data from controller to jsp you can use JSTL to iterate through the data and pass it to javascript. 或者,如果要将数据从controller传递给jsp ,则可以使用JSTL遍历数据并将其传递给javascript。

In this kind of situation, I prefer to serialize the Java List object into a JSON string in the controller, and pass that string to the jsp. 在这种情况下,我更喜欢在控制器中将Java List对象序列化为JSON字符串,然后将该字符串传递给jsp。 Assuming your list contains instances of a class that looks like this, 假设您的列表中包含此类的实例,

public class MyObject {
    protected String X;
    protected int Y;

    // getters, setters, other methods and fields...
}

You can use libraries like Gson or Jackson to serialize the list in your controller. 您可以使用GsonJackson等库来序列化控制器中的列表。

List<MyObject> list = new ArrayList<MyObject>();
// add some objects to the list...

String json = new Gson().toJson(list);
request.setAttribute("values", json);

In your jsp, the values request attribute is a string representing a complete javascript object in JSON. 在您的jsp中, values请求属性是一个字符串,代表JSON中的完整javascript对象。

var data = {
    values: ${values}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM