Populating JavaScript Array from JSP List

后端 未结 3 807
[愿得一人]
[愿得一人] 2020-12-01 16:24

Ok so perhaps someone can help me with a problem I\'m trying to solve. Essentially I have a JSP page which gets a list of Country objects (from the method referenceData() fr

相关标签:
3条回答
  • 2020-12-01 17:01
    var countries = new Array();
    <c:forEach items="${countryList}" var="country" varStatus="status"> 
        countryDetails = new Object();
        countryDetails.country = ${country.name}; 
        var provinces = new Array();
    
            <c:forEach items="${country.provinces}" var="province" varStatus="provinceStatus"> 
               provinces.push(${province.name});
            </c:forEach> 
        countryDetails.provinces = provinces;
        countries.push(countryDetails);
    </c:forEach> 
    

    now what you have is something like this in javascript

    var countries = [
      {country:"USA",
      provinces: [
        "Ohio",
        "New York",
        "California"
      ]},
      {country:"Canada",
      provinces: [
        "Ontario",
        "Northern Territory",
        "Sascetchewan"
      ]},
    ]
    

    The other option would be to make your output look like the javascript I posted.

    var countries = [
    <c:forEach items="${countryList}" var="country" varStatus="status">  
        {country: '${country.name}',
        provinces : [ 
            <c:forEach items="${country.provinces}" var="province" varStatus="provinceStatus">  
               '${province.name}'
               <c:if test="${!provinceStatus.last}">    
                 ,    
               </c:if>   
            </c:forEach>  
        ]}
        <c:if test="${!status.last}">    
          ,    
        </c:if>  
        </c:forEach>  
    ];
    
    0 讨论(0)
  • 2020-12-01 17:11

    Have you considered using JSON? There are several libraries out there that can take a generic collection and output JSON for Java and other languages.

    0 讨论(0)
  • 2020-12-01 17:18

    The primary problem in your code is that you forgot to put "status.index" inside ${ }.

    countries[${status.index}] = new Array();
    

    Now, that said, that would be a pretty bad way to do things because you'd end up with a lot of Javascript code in your page. Much much better to create the list using Javascript object notation as in the second of @John Hartsock's answers.

    0 讨论(0)
提交回复
热议问题