I have a servlet which has a variable which holds a JSON string.
JSONObject obj = new JSONObject();
obj.put("parameter", jsonList);
request.setAttribute("jsonstring", obj.toString());
RequestDispatcher rd = request.getRequestDispatcher("/file.jsp");
rd.forward(request, response);
Now I am forwarding my request and response objects to a JSP page which contains a JS file. How can I access the value of jsonstring variable inside the JS file.As I need to parse my JSON string further using jQuery.
I tried doing this in my JS file as I saw in some of the posts online.But it seems like its not working for me.
var test = '<%=request.getAttribute("jsonstring")%>'
Kindly guide me on the same.Thanx.
I have a servlet which has a variable which holds a JSON string.
JSONObject obj = new JSONObject();
obj.put("parameter", jsonList);
request.setAttribute("jsonstring", obj.toString());
RequestDispatcher rd = request.getRequestDispatcher("/file.jsp");
rd.forward(request, response);
Now I am forwarding my request and response objects to a JSP page which contains a JS file. How can I access the value of jsonstring variable inside the JS file.As I need to parse my JSON string further using jQuery.
I tried doing this in my JS file as I saw in some of the posts online.But it seems like its not working for me.
var test = '<%=request.getAttribute("jsonstring")%>'
Kindly guide me on the same.Thanx.
Share Improve this question asked Jan 30, 2014 at 13:07 ArpitArpit 3733 gold badges6 silver badges11 bronze badges4 Answers
Reset to default 7If the JSP file uses a <script>
tag to load an external JavaScript file, something like this:
<script type="text/javascript" src="js/yourFile.js"></script>
then it won't work. What you have is a JSP scriptlet which only means something during the execution of the JSP file. That yourFile.js
file won't be parsed server-side because it doesn't need to be. Only the browser will know what to do with the <script>
tag and issue a request to the server to load the JavaScript.
In these cases what you can do is something like this inside your JSP:
<script type="text/javascript">
var test = <%=request.getAttribute("jsonstring")%>;
</script>
<script type="text/javascript" src="js/yourFile.js"/></script>
Since the JSP scriptlet is inside your JSP file it now actually gets processed correctly, and instead outputs the valid JSON for the object/array to store in the globally scoped test
variable, which you can then refer to inside yourFile.js
.
Try this :
var test = <%=request.getAttribute("jsonstring")%>;
Else try that :
var test = eval('<%=request.getAttribute("jsonstring")%>');
The solution for me was the following:
<script type="text/javascript">
var value =<%=request.getAttribute("indicadorId") %>;
</script>
put object direct in the request like this
request.setAttribute("jsonstring", obj);
then assign request obj to js variable, it will be accessable as json object;
var test = <%=request.getAttribute("jsonstring")%>;
... = test.parameter;