简体   繁体   中英

Pass variable from JSP to Javascript

Inside a JSP, I am fetching data from a Servlet by this code

<%
String name=(String)request.getAttribute("filepath");
%>

I want to access this inside script tags, how should i go about it? I tried this var n = "${name}" and var n = "<%=name%>" and it did not work.

Both options should work fine (do not forget the ;).
Just remember that the scriptlet/ EL are executed when the page is returned from the server and the JavaScript when the browser parse the HTML.

To debug this issue I would use scriptlet first and look if I have a value using browser "view source". If you do not see any value ie

var n = "";

You did not set the attribute correctly in java. As for EL usage. Make sure you have the correct setting, in older version EL was disabled by default see http://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el/

Make sure the assignment in scriptlet is working. Try System.out.println(name); to see if the value is set correctly.

I often use the latter

var n = "<%=name%>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM