3

Is it possible to convert jstl/JSP variables to javascript variables?

Here is the JSTL:

 <c:forEach var="responseString" items = "${responseString}">
     <c:out value="${responseString.response}" />  
 </c:forEach>

I want to transfer the value inside ${responseString.response} to a javascript var response

HERE is the javascript function:

directionsService.route(request, function(response, status)

I tried this tutorial;

var response = {
<c:forEach var="responseString" items = "${responseString}">
    <c:out value="${responseString.response}" />
</c:forEach>
}

Obviously it didn't work, I kind of screwed it up, please help.

Added info, ${responseString.response} is actually JSON, I just converted it to String:

{"routes": [{"bounds" : {"northeast":{"lat":14.650,"lng":121.050610}, "status":"OK"}

It's a deeply nested JSON.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
PHil
  • 51
  • 2
  • 5
  • 1
    Can you simply put `var response = ` before the JSON string? If it's valid JSON it should work correctly. You might look at a JSON library and then decode/reencode for display. – artlung Jun 07 '12 at 05:44
  • @artlung, the JSON is actually from google map api, i already had parsed the JSON, passed it as STRING, but i cant convert the string to javascript variable – PHil Jun 07 '12 at 05:48

2 Answers2

1

Do something like this:

  var availableTags = [
  <c:forEach items="${vendorMap}" var="vendor" varStatus="vendorStatus">
     '<c:out value="${vendor}" />'
     <c:if test="${!vendorStatus.last}">    
     ,    
     </c:if> 
  </c:forEach>
 ];

Note that you should not add "," for the last entry and also single quotes

Shweta
  • 924
  • 14
  • 23
0

Since you use for each, I assume it will be more than one response, thus instead var response = { you should use array []. Try:

var response = [
<c:forEach var="responseString" items = "${responseString}">
    <c:out value="${responseString.response}" />,
</c:forEach>
];

Notice , after each element.

edit on request:

for(var i in response){
   PUSH_TO_GOOGLE_MAPS_WIDGET(response[i]);
}

response[i] will be like {"routes": [{"bounds" : {"northeast":{"lat":14.650,"lng":121.050610}, "status":"OK"}.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
  • it still doesnt work, if i add your code, google maps i previously had disappears, i would assume, something is wrong. the code is written within – PHil Jun 07 '12 at 06:23
  • the ${responseString.response} is just a plain String in JSON format. how can i transfer it to javascript **var** using JSTL foreach? please help. – PHil Jun 07 '12 at 06:28
  • I don't know what are u going to do with response next, if u want to get every single response from response array and push it to google maps widget you must iterate over `response` array... – IProblemFactory Jun 07 '12 at 06:29
  • thatis what i want to do, push it to google maps. how do you iterate over response? can you give exmple pelase – PHil Jun 07 '12 at 07:00