我想将jsf文件中的对象列表(在示例中为list_A)传递给javascript中的函数。问题是调用event.name =“#{controllerManagedBean.list_A.get(y).getName()}”;为event.name分配值,就好像“ y”始终为0,即列表中的第一项。
如何浏览列表并将所有名称传递给list_1(如果可能,不使用json)?
谢谢!
这是我的代码(我想重要的是脚本):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<script src="visJS/dist/vis.js"></script>
<link href="visJS/dist/vis-timeline-graph2d.min.css" rel="stylesheet" type="text/css" />
</h:head>
<h:body>
<h:form>
<h:dataTable value="#{controllerManagedBean.list_A}"
var="evento" border="2"
cellspacing="1" cellpadding="1">
<h:column>
<f:facet name="header">Evento</f:facet>
#{evento.nombre}
</h:column>
</h:dataTable>
</h:form>
<div id="timeline">Prueba</div>
<script src="js/timeline.js"></script>
<script>
var x = parseInt('#{controllerManagedBean.list_A.size()}');
var list_1 = new Array();
//<![CDATA[
for(var y = 0; y<x; y++){
//]]>
var evento = new Object();
evento.nombre = "#{controllerManagedBean.list_A.get(y).getNombre()}";
list_1.push(evento);
}
myFunction(list_1);
</script>
</h:body>
</html>
我终于通过JSON解决了@ fuggerjaki61所说的问题
使用ui:repeat的@Kukeltje解决方案对我不起作用,因为ui:repeat不能放在脚本块中。但是,非常感谢!
我的解决方案是:在服务器部分(这是一个Web应用程序)中,我放置了一个通过列表list_A并生成包含所有数据的JSON格式字符串的函数。
private String listInJSON;
public void convertToJson()
{
Gson gson = new Gson();
listInJSON = "";
listInJSON += "[";
for(MyObject obj: list_A){
listInJSON += gson.toJson(obj);
listInJSON += ",";
}
listInJSON += "]";
listInJSON = listInJSON.replace("},]", "}]");
}
这会生成JSON格式的字符串:[{...},{...},... {...}]例如就我而言:[{“ name”:“ Prueba”,“ date”:“ 1999年9月10日12:00:00 AM”},...]
在我的index.html中,我调用了javascript函数procesarJSON:
onclick="procesarJSON('#{controllerManagedBean.listInJSON}')"
最后,在我的JavaScript文件中:
function procesarJSON(jsonCompleto){
var obj = JSON.parse(jsonCompleto);
for (var i = 0; i < obj.length; i++)
{
console.log('name = ' + obj[i].name); // prints: Prueba
// Remember the JSON: [{"name":"Prueba","date":"Sep 10, 1999 12:00:00 AM"}, ...]
// To process the rest of the data here.
}
}
感谢所有人!