繁体   English   中英

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

[英]send data from bean to javascript with json in jsf

我想将我的arraylist从managedBean发送到javascript代码,

我的豆在这里:

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和resources类。 这是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\",\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;
}

}

现在对我们的JavaScript进行修改。 将用于生成图表的匿名函数命名为函数,例如:generateChart(CityData)并使用数据修改行:变为数据: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,在数据加载之后,开始生成图表。

成功。

暂无
暂无

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

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