4

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.

2
  • 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. Commented Jun 7, 2012 at 5: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 Commented Jun 7, 2012 at 5:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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"}.

4 Comments

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 <script type="text/javascript"> right? sory 4 being noob
the ${responseString.response} is just a plain String in JSON format. how can i transfer it to javascript var using JSTL foreach? please help.
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...
thatis what i want to do, push it to google maps. how do you iterate over response? can you give exmple pelase

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.