I am not sure if this is possible, but can you pass the value of a string from Java file (Struts action) to jQuery (which is in custom.js, not in JSP)? The action file generates a JSON data, and I want the data to be passed to the jQuery.
2 Answers
If your code is something like this:
<script>
var msg= <%=msg%>;
</script>
<script src="files/js.js"></script>
You can do:
var msg= '<%= msg %>';
Then you can assign your msg variable to JQuery as you prefer, e.g.:
$(msg);
Note that you could need to use StringEscapeUtils.escapeJavaScript function beforehand to sanitize your string.
Separate JS file
If you want to pass this string to a JS separate file, you can do it in an elegant and efficient way.
In your file.js:
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
alert('Hello World! -' + _args[0]);
}
};
}());
In your JSP page:
<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["msg", 1, "othervalue..."]);
MYLIBRARY.helloWorld();
</script>
5 Comments
what do you mean with "data to be passed to the jquery"?
the key words you should focus on are: client and server.
server produces the datas and server consumes it.
how? you build a web-api rest method with your preferred framework/library (struts in your case) and then via $.ajax method consume it.