如何将数组从struts2散列到未指定大小的javascript数组?

kra*_*say 3 javascript for-loop struts2 hashtable

我正在尝试根据用户在下拉框中选择的内容更新图像(无需单击提交或任何内容),我已经让它工作,除了一件事 - 它有一个上限到多少选项可用:

var hash = new Array();
hash['<s:property value="itemLists[1][0].id"/>']=0;
hash['<s:property value="itemLists[1][1].id"/>']=1;
hash['<s:property value="itemLists[1][2].id"/>']=2;
hash['<s:property value="itemLists[1][3].id"/>']=3;
hash['<s:property value="itemLists[1][4].id"/>']=4;
hash['<s:property value="itemLists[1][5].id"/>']=5;
hash['<s:property value="itemLists[1][6].id"/>']=6;
hash['<s:property value="itemLists[1][7].id"/>']=7;
var item= new Array();
item[0] = '<s:property value="itemLists[1][0].image"/>';
item[1] = '<s:property value="itemLists[1][1].image"/>';
item[2] = '<s:property value="itemLists[1][2].image"/>';
item[3] = '<s:property value="itemLists[1][3].image"/>';
item[4] = '<s:property value="itemLists[1][4].image"/>';
item[5] = '<s:property value="itemLists[1][5].image"/>';
item[6] = '<s:property value="itemLists[1][6].image"/>';
item[7] = '<s:property value="itemLists[1][7].image"/>';
Run Code Online (Sandbox Code Playgroud)

这显然太具体了,我想知道是否有办法说出一个for循环为列表中的每个项目执行此操作.问题来自struts2 - '<s:property value="itemLists[1][#].id"/>'在页面首次加载时进行评估,并且'string'不能分解为两个部分,中间有一个迭代器变量.有没有办法在Javascript函数中使用带有struts2数组的for循环?

Dav*_*ton 5

上述循环之一的大约(读取:未经测试):

var items = [];
<s:iterator list="itemLists[1]" var="item" varStatus="stat">
  items.push('<s:property value="#item[#stat.index].image"/>');
</s:iterator>
Run Code Online (Sandbox Code Playgroud)

您还需要JS-escape字符串以避免破坏.


我质疑单独的数组.JS有匿名对象表示法,例如{ id: 0, image: "ohai" }.我会用那个; 它使事情更容易处理.它看起来更接近这个:

var items = [];
<s:iterator list="itemLists[1]" var="item" varStatus="stat">
  items.push({
    id:    '<s:property value="#item[#stat.index].id"/>',
    image: '<s:property value="#item[#stat.index].image"/>
  });
</s:iterator>
Run Code Online (Sandbox Code Playgroud)

所有JSP标记都是创建要发送到客户端的文本.

文本是什么并不重要 - 它没有理由不能成为JavaScript源代码.

您还可以将数据公开为JSON /直接JS,并避免繁忙的工作.