在jsf中使用json将数据从bean发送到javascript



我想把数组列表从managedBean发送到javascript代码,

my bean is here:

public void getDataAsJson(){
    String [] dizi={"Tokyo","Jakarta","New York","Seoul",
              "Manila","Mumbai","Sao Paulo","Mexico City",
              "Dehli","Osaka","Cairo","Kolkata",
              "Los Angeles","Shanghai","Moscow","Beijing",
              "Buenos Aires","Guangzhou","Shenzhen","Istanbul"};
    Random rnd =new Random();
    JSONObject obj= new JSONObject();
    for (int i = 0; i < dizi.length; i++) 
        obj.put(dizi[i], new Integer(rnd.nextInt(80)));
}

我的javascript代码在这里的XHTML页面:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
<!--
$(function () {
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                zoomType: 'xy'
            },
            title: {
                text: 'avarage'
            },
            subtitle: {
                text: ''
            },
            xAxis: [{
                gridLineWidth: 0.5,
                categories: [// here is my city names which come from mybean]
            }],
            yAxis: [{ // Primary yAxis
                labels: {
                    formatter: function() {
                        return this.value;
                    },
                    style: {
                        color: '#89A54E'
                    }
                },
                title: {
                    text: 'avarage',
                    style: {
                        color: '#89A54E'
                    }
                }
            }],
            series: [{
                name: 'avarage',
                color: '#89A54E',
                type: 'spline',
                data: [// // here is my city's avarage which come from mybean],
                       labels: {
                        rotation: -90,
                        align: 'right',
                        style: {
                            fontSize: '13px',
                            fontFamily: 'Verdana, sans-serif'
                        }
                    }
            }]
        });
    });
});
//-->
</script>

这是我的XHTML页面正文:

<body>   
  <script src="http://code.highcharts.com/highcharts.js"></script>
  <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body> 

您需要理解JSF在这个问题的上下文中仅仅是一个HTML/JS代码生成器。

您只需要让JSF 以这种方式打印所需的数据,使其最终成为语法有效的JS代码。

categories: #{bean.dataAsJson}

其中getDataAsJson()返回表示所需JSON代码的String。例如:基本上:

public String getDataAsJson() {
    return "['foo', 'bar', 'baz']";
}

要验证结果,请在浏览器中右键单击页面并执行查看源

categories: ['foo', 'bar', 'baz']

通过JSF Bean发送数据到javascript例程不是一个好主意,但我的解决方案是使用java web服务或JAX-RS。java web服务包含2个类,JaxRsActivator和资源类。下面是JaxRsActivator的源代码:

package service;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}

资源类的源代码

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",rn" + 
            ""Manila","Mumbai","Sao Paulo","Mexico City",rn" + 
            ""Dehli","Osaka","Cairo","Kolkata",rn" + 
            ""Los Angeles","Shanghai","Moscow","Beijing",rn" + 
            ""Buenos Aires","Guangzhou","Shenzhen","Istanbul"};rn";
    return s;
}

}

现在是JavaScript中的一个修改。将生成图表的匿名函数设置为命名函数,例如:generateChart(CityData),并将data:修改为data: CityData。你的JavaScript以:

开头
$(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
}

//JavaScript结束

也把这个JavaScript放在JSF页面的末尾。页面加载完成后,开始JavaScript加载数据,数据加载完成后,开始生成图表。

成功。

相关内容

  • 没有找到相关文章

最新更新