Menkot
Menkot

Reputation: 734

How to get int array with javascript in play framework template?

When I tried to pass a list to the template I got an error.

The list is defined like:

myList: List<Map<String,int[]>>

Now the data of myList is :

[{First Try=[1,0,0,1], Second Try=[1,1,2,2]}, {}]

I use chart.js to show a chart and so I need a int[] as data list.

my view:

@(myList: List[Map[String,Array[Int]]])

var list = @myList;
for(var i=0;i<list.length;i++){
    var map = list[i];
    for(var key in map){
        myFunction(key,map[key]);
    } 
}

myFunction(string,array){
//I want directly use the array to the chart’s datasets
//others

var myChart = new Chart(chartid, {
    type: 'bar',
    data: {
        labels: [“a”, “b", “c”, ”s”],
        datasets: [{
            data: array
        }]
    }
}

But I got error when I try to traversal the List (The error line shown with Chrome debug)

var out = [{First Try=[I@6e37161d, Second Try=[I@5788d8a9}, {}];   
// “Uncaught SyntaxError: Invalid or unexpected token”.

I know when directly output array with

System.out.println(array);

in java it will happen with the string like [I@6e37161d, but I don’t know how to deal with it in javascript.How can I use this array?I will be grateful if anyone can help .

Thank you very much.

Upvotes: 2

Views: 635

Answers (1)

Samuel
Samuel

Reputation: 17171

You can't convert the Java object directly to a Javascript variable like you're attempting to do.

var list = @myList;

That just takes myList.toString() and attempts to set that as a literal Javascript variable. You need to serialize your Java object to JSON first, then you can parse the JSON in Javascript. Like so:

// Java controller code
String myListJson = Json.stringify(Json.toJson(myList));

// Template
@(myListJson: String)
var list = JSON.parse("@myListJson");

Upvotes: 2

Related Questions