I know there is already questions about that, but I just canĀ“t simply get this work, I have a JSP file with a java variable in it:
String test = "Hello";
And I need to read this value in the Javascript embedded in the same JSP file, I tried so many options, but it is not working, and for security I don't want pass the value using the URL or hidden values.
Any ideas of how get this working?
The best way to do it is to use something like following in your javascript code;
var myvar = '${jspvar}';
I know this one is old, but this worked for me:
var javaScriptVar="<%out.print(javaString);%>";
you need to make sure that if you are using an external js file (out of the jsp file), the above line has to be before the "include" script tag. for example this is the jsp file:
var javaScriptVar="<%out.print(javaString);%>";
<script src="some_location/test.js"></script>
You can pass the value by calling some methods in html part..
<input type="submit" value="view" onclick="callpro('<%= varname %>')" />
var jsvariable="<%=test%>";
One thing to note is that you could namespace those variables in this way:
var MYAPP.javaScriptVar="<%out.print(javaString);%>";
The technique is from "Javascript: The Good Parts" Book.
Related
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
Is there any way that i can get a variable that i've declared in JavaScript Function to the JSTL tags ?
Javascript
var abc = document.getElementById('asdf').value;
here is the JSP:
<input type="hidden" id="asdf" value="onetwothree" />
and i want to declare the C:set from the JavaScript
<c:set var="ex" value="${abc}" />
The purpose it to get "ex" variable with the value "onetwothree".
Sorry for the rough explanation. Thanks
you are doing it other way. it is possible to access a variable declared in jsp from javascript using below code
<c:set var="ex" value="test" />
<script type="text/javascript">
var abc = '${ex}';
</script>
but other way around as you mentioned above is not possible
If you are looking to modify DOM based on what is provided in input box then I would suggest to use code like below (in javascript)
var abc = document.getElementById('asdf').value;
// assuming you want to print this value in a label
document.getElementById('mylabel').innerHTML = abc;
In short if you want to do any change in DOM based on client input, do it through javascript instead of relying on JSP
You can't access JSTL tags from Javascript, simply because those tag exists only server side (client side they are replaced by plain HTML).
You can always send the javascript var as request parameter, then use it server side.
is there a way to move a javascript function-arg into JSTL tag?
function loadList(listName)
{ <c:forEach var="item" items="${listName}"> .... }
Why did this code"
x = '${item.category}';
work all good and suddenly it didn't work , but change to
x = "${item.category}";
does work ? I did alert( message )in page load to check if the page load success.
I don't think it is possible to put a javascript variable into a JSTL tag without a "postback" or reload of the page. However, the reverse (i.e., putting a JSTL tag value into a javascript variable) should be possible.
The reason is the separation between server-side (JSTL) and client-side (Javascript) code.
With 1st question as what I know, you cant. Instead the reverse of it as your example in 2nd question. As what #jordan mentioned.
In your 2nd question, I'm not sure why, may be you pass a value with ' or single qout on the list.category.
I have tried:
<!--...-->
<script type="text/javascript">
var myVar = "some string";
</script>
<!--...-->
<input name="&{myVar};" ... />
<!--...-->
But using FireFox, the name is set to the literal string: "&{myVar};" instead of the value of myVar...
UDPATE: I see this called JavaScript Entities and hasn't been supported for a long time - but there must be way if one can include JavaScript directly in events (I realize attributes are not events, so JavaScript probably isn't evaluated).. ?! It would be a lot nicer than hardcoding the value as it used elsewehere a lot..
var myInput = document.createElement('input');
myInput.setAttribute('name', myVar);
someContainElement.appendChild(myInput);
I'm afraid you have to use Javascript to manipulate the html element.
You can use jQuery to make this easier:
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<input id="myInput" .../>
<script>
var myVar = "value";
$("#myInput").attr("name", myVar);
</script>
Here's what you need to do.
Start by never reading javascript tutorials from a Java site again. Different monsters entirely, plus the tutorials on the site you're referencing are horrible.
Second, get a copy of Javascript the Good Parts, http://www.amazon.com/dp/0596517742/
This book is perhaps the most useful book ever written (in my opinion) about the language itself. It doesn't say anything about dealing with DOM API's.
I encourage you to learn the language itself before getting too deep into javascript libraries like jQuery. It'll do you a load of good sooner rather than later.
Once you're at least somewhat familiar with the proper ways to use javascript as a language, start investing your time into one library or another. jQuery is probably the most used, well loved, and kindest library out there. It will make dealing with cross-browser crap SO much easier for you.
Both Phil's and Xenoflex's ways, are the better way to go. They are actually doing the same thing just different ways, one using jQuery the other pure Javascript.
Alex's will work as well but then everything is hardcoded and somewhat less flexiable to future changes. The way Alex left his answer open you could print the string or assign it to a variable to be appended to a javascript object.
I think the nearest match to what you're looking for is:
<script type="text/javascript">
var myVar = "some string";
</script>
...
<script type="text/javascript">
document.write('<input name="' + myVar + '" ... />')
</script>
But as I said you should really take one of the first two approaches.
I have a Grails variable which is of type JASONList that is rendered in a template.
Is there a way to access this list from inside a JavaScript function?
Let's say I want onresize to fit all the objects on the screen. Without making a database call and refetching the entire list from Ajax...
Let's say the template does something like this:
<g:each var="report" in="${reportList?.myArrayList}">
<li style="display:inline; list-style:none;">
<img src=" ${report?.img}">
</li>
</g:each>
<script type="text/javascript">
function resize(list) {
if (list.size <givenSize) // Pseudocode
list.subList() // Pseudocode
}
window.onresize = resize("${reportList}")
</script>
The problem with this is that for some reason Grails gsp does not render "${reportList}" as a list. Instead it renders it as the string "${reportList}".
I am probably thinking of this problem completely wrong, but is there a way to resize these objects or get them through document.getElementById or something of that nature?
The $reportList is populated by POJO as JSON conversion...
Grails variables only exist on the server side. JavaScript runs in the browser (client side). Everything that's sent to the browser is a string, so while you can use Grails to generate a piece of JavaScript like window.onresize = resize("${reportList}"), the browser will only see the string that ${reportList} evaluates to.
That means that, if you use Grails to pass a variable to the resize() JavaScript function, the parameter (list) will only ever be a string - you won't be able to access server-side list methods like list.size or list.subList(), because the list variable is no longer a list; it's just a string.
I don't know, but maybe Grails doesn't want to evaluate expressions inside script tags. Dynamically generated scripts is not a very good practice.
But until you find the exact cause, you could try something like this:
<g:each var="report" in="${reportList?.myArrayList}">
<li style="display:inline; list-style:none;">
<img src=" ${report?.img}">
</li>
</g:each>
<%= """<script type=\"text/javascript\">
function resize(list){
if(list.size <givenSize) //posudo code
list.subList() // psudocode
}
window.onresize = resize(\"$reportList\")
</script>""" %>
I'm not sure why your ${reportList} is being rendered as ${reportList}, because when I do the following:
var t = "${taskList}";
I get the following in my HTML:
var t = "[com.wbr.highbar.Task : 1, com.wbr.highbar.Task : 4, com.wbr.highbar.Task : 2, com.wbr.highbar.Task : 5]";
That said, you're still going to have issues, because JavaScript will have no idea what to do with your reportList. If it is pure JSON, you would need to eval() it so that it gets turned into a JavaScript Object.
I figured out my problem. Basically if you are using POJO in Grails the Grails as JSON conversion is not very smart. All it does is a toString on the object instead of potentially looking at all the public accessors, etc.
It is kind of disappointing, but basically I need to create the JSON conversion in the toString method of my POJO.