Search code examples
javascriptarraysjaggery-js

call a jaggery Array inside javascript


I have a jag file which will contain an array. Inside that jag file I also have a javascript function, what I want to do is to call the array inside that javascript

<%
var types = jsonObj.component.type;
var typeId = new Array();
var typeRole = new Array();
for(var i=0;i<jsonObj.component.type.length;i++) {
    typeId[i] =types[i].id;
    typeRole[i] =types[i].roles;
}
log.info("----------"+typeId[0]+ typeRole[0]);
%>

in the same file ,

<script type="text/javascript">
function generateResponse() {

}
</script>

I want to read the array typeid inside the generateResponse function.


Solution

  • Your first snippet is a server side template, which is going to be executed before generateResponse is loaded by the user's browser. There are a few ways to get around this but the easiest would be to insert a script tag with a variable equal to your array, and then use that variable in your script below:

    <%
    var types = jsonObj.component.type;
    var typeId = new Array();
    var typeRole = new Array();
    for(var i=0;i<jsonObj.component.type.length;i++) {
        typeId[i] =types[i].id;
        typeRole[i] =types[i].roles;
    }
    log.info("----------"+typeId[0]+ typeRole[0]);
    %>
    
    <script> var typeId = <%= typeId %>;</script>
    

    The variable typeId should now be accessible in your generateResponse function.

    I would also suggest transforming your data before you hit the template, but that's just me.