2

i used these code but nothing seen on document

            <%String movie_name ="Matrix"; %>
            <script type="text/javascript">
                var movie_name="";
                movie_name= <%= movie_name%>;
                document.write(movie_name);
            </script>

so anyone can help me to convert java string to javascript string ?

2
  • 1
    Is it a JSP page? Are you setting request.setAttribute("movie_name", "The Matrix") or a parameter names movie_name? Did you read this tutorial. Did not downvote though. Commented Feb 27, 2012 at 8:08
  • oh sorry, I really did not meant to embarrass you. The question looked like it could have been solved by a little more reading of JSP specs or a tutorial. Commented Feb 27, 2012 at 8:29

2 Answers 2

6

This might do it (missing quotes):

movie_name="<%= movie_name%>"

Also looking at your sample code you can replace it completely with:

<%= movie_name%>

Finally consider using .

Sign up to request clarification or add additional context in comments.

3 Comments

Quote alone are only enough in a very limited set of circumstances.
@T.J.Crowder: are you concerned about escaping? That's why I mentioned about JSTL, e.g. <c:out value="${movie_name}" escapeXml="true" />.
Yes. Just showing putting it in quotes leads the OP down a path that will trip him up at some point. And yes, I was just about to add that showing an example of how to do it correctly with the JSTL would be more helpful than just saying "use JSTL". I'd put that in the answer. (Is escapeXml really the right way to output a JavaScript string literal?)
2

you need to wrap your output in quotes (I'm assuming this is JSP?)

movie_name = "<%= movie_name %>";

See, when this is written out the browser tries to interpret it, so without quotes you wind up with something that looks like...

movie_name = Men In Black;

Since this is obviously a massive syntax fail, the browser just quits trying and silently fails (though you should see a log of what it didn't like).

When you wrap the output in quotes then everything falls into place HOWEVER, make sure to convert any " in your java string to \" when you print it out, or you'll have more of the same trouble.

However, as the other answers suggest, you're re-inventing the wheel here and should just do this the prescribed way, as per Nishant's advice.

1 Comment

Quote alone are only enough in a very limited set of circumstances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.