0

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 2

3

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>
Sign up to request clarification or add additional context in comments.

5 Comments

How about I want to pass the string to a JS file, not in JSP?
And my String is in a Java file, not in JSP.
Updated the answer to feed an external JS file
For the second comment, you can simply pass the string from your Java file to your JSP file as usual...
Don't forget to escape the single-quotes in the JSP when injecting the JavaScript string literal.
0

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.

1 Comment

I have an Action class that generates data in JSON format. I want the program to pass that data in JSON format from my Java file to jQuery.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.