I want to send my arraylist from managedBean to javascript code,
my bean is here:
public void getDataAsJson(){
String [] dizi={\"Tokyo\",\"Jakar
Send data to javascript routine via JSF Bean is not good idea but my solution is working with java web service or JAX-RS. The java web service contains 2 classes, JaxRsActivator and resources class. Here is source code of JaxRsActivator:
package service;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}
Here is source code of resource class.
package service;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/resource")
@Produces(TEXT_PLAIN)
public class resource {
@GET
@Path("cities")
public String dizi() {
String s = "{\"Tokyo\",\"Jakarta\",\"New York\",\"Seoul\",\r\n" +
"\"Manila\",\"Mumbai\",\"Sao Paulo\",\"Mexico City\",\r\n" +
"\"Dehli\",\"Osaka\",\"Cairo\",\"Kolkata\",\r\n" +
"\"Los Angeles\",\"Shanghai\",\"Moscow\",\"Beijing\",\r\n" +
"\"Buenos Aires\",\"Guangzhou\",\"Shenzhen\",\"Istanbul\"};\r\n";
return s;
}
}
Now a modification in our JavaScript. Make your anonymous function for generating chart a named function e.g.: generateChart(CityData) and modify line with data: becomes data: CityData, Your JavaScript start with:
$(function () {
var xhr = new XMLHttpRequest();
// replace the dots
var url = "http://localhost:8080/........../resource/cities";
xhr.onreadystatechange = function() {
// Check if fetch request is done
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
// Parse the JSON string
var jsonData = eval(xhr.responseText);
generateChart(jsonData);
}
};
// Do the HTTP call using the url variable we specified above
xhr.open("GET", url, true);
xhr.send();
function generateChart(CityData) {
// put your code for generating your chart
// modify line
data: CityData
}
// End of JavaScript
Put also this JavaScript on the end of your JSF page. After the page loading start the JavaScript with data loading and after the data loading start the chart generation.
succes.
You need to understand that JSF is in the context of this question merely a HTML/JS code generator.
You just need to let JSF print the desired data in such way that it ends up in syntactically valid JS code.
categories: #{bean.dataAsJson}
Wherein getDataAsJson()
returns a String
representing the desired JSON code. E.g. basically:
public String getDataAsJson() {
return "['foo', 'bar', 'baz']";
}
To verify the result, rightclick page in browser and do View Source.
categories: ['foo', 'bar', 'baz']