2012-07-05 67 views
0

我們通常在jsp上做這樣的JSTL ......但我現在需要使用JSON在JavaScript中設置數據。我怎麼會做在Javascript中這樣的事情/ JSON在Javascript中遍歷bean?

在豆基本上環路和拔出它的參數:

<c:forEach var="field" items="${detFields}"> 
     ${field.groupName} 
      ${field.breakoutAllowed}   
</c:forEach> 

這樣我就可以把它裏面的東西是這樣的:

"data": [{ 
     "value": "${field.groupName}" 

    }, { 

     "value": "${field.breakoutAllowed}" 
    }] 

回答

1

它看起來像你正在尋找的JSON結構是一個對象數組,每個對象都有兩個屬性:namebreakoutAllowed。將這些數據分配給變量的JavaScript可以像這樣從JSP文件中輸出。 (在一個<script>塊或等效的,當然。)

var output = [ 
<c:forEach var="field" items="${detFields}" varStatus="status"> 
    { 
    "name":"${field.groupName}", 
    "breakoutAllowed":"${field.breakoutAllowed}" 
    } 
    <c:if test="${not status.last}">,</c:if> 
</c:forEach> 
] 
+0

我想這不能寫在JSP文件的中間,因爲整個事情是一個JavaScript?我們可以將這些值存儲在字符串類型的參數中,然後使用JQuery引用它們,然後將它們拆分爲JSON ...我有點誤導了嗎? – 2012-07-05 19:39:48

+1

@ShivKumarGanesh是的,這將在JSP中進行,但我對於我猜測的整個事情有點不清楚。希望編輯澄清一些事情。 – 2012-07-05 19:46:33

+0

+1現在輸出一個完美的陣列!但我仍然會提供另一種解決方案。只要讓我知道你看起來不錯。 – 2012-07-05 19:57:19

1

希望這個代碼工作得很好,是你喜歡的。我認爲將scriptlet編寫成JS是一種有點奇怪的做法,所以只是提出了另一種處理它的方法。如有必要請發表評論。

$(document).ready(function(){ 
    var k=$('#data').val(); 

    //Convert the value into the required array. Since writing it is JavaScript directly is not a daily practice. 
    }) 

    <input type="hidden" id="data" value= 
    <c:forEach var="field" items="${detFields}" varStatus="status"> 
     { 
     "name":"${field.groupName}", 
     "breakoutAllowed":"${field.breakoutAllowed}" 
     } 
     <c:if test="${not status.last}">,</c:if> 
    </c:forEach> 

    />