簡體   English   中英

如何將數組從struts2散列到未指定大小的javascript數組?

[英]How can I hash an array from struts2 to a javascript array of unspecified size?

我正在嘗試根據用戶在下拉框中選擇的內容更新圖像(無需單擊提交或任何內容),我已經讓它工作,除了一件事 - 它有一個上限到多少選項可用:

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"/>';

這顯然太具體了,我想知道是否有辦法說出一個for循環為列表中的每個項目執行此操作。 問題來自struts2 - '<s:property value="itemLists[1][#].id"/>'在頁面首次加載時進行評估,並且'string'不能分為兩部分中間的迭代器變量。 有沒有辦法在Javascript函數中使用帶有struts2數組的for循環?

上述循環之一的近似(讀取:未經測試):

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

您還需要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>

所有JSP標記都是創建要發送到客戶端的文本。

文本是什么並不重要 - 它沒有理由不能成為JavaScript源代碼。

您還可以將數據公開為JSON /直接JS,並避免繁忙的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM