send data from bean to javascript with json in jsf

前端 未结 2 510
面向向阳花
面向向阳花 2021-01-13 08:58

I want to send my arraylist from managedBean to javascript code,

my bean is here:

public void getDataAsJson(){
    String [] dizi={\"Tokyo\",\"Jakar         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 09:22

    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.

提交回复
热议问题