CaptainLevii
CaptainLevii

Reputation: 71

Uncaught ReferenceError:some_string is not defined

In controller class, I have added

model.addObject("hostname", hostname);

and tried to catch it in my jsp page with

var hostname=<%=request.getAttribute("hostname")%> ;

Yet, this is throwing error

Uncaught ReferenceError:**some_string** is not defined

What can be done to avoid this?

Upvotes: 0

Views: 1153

Answers (1)

Quentin
Quentin

Reputation: 944169

Remember: You are not passing a variable from one program to another, you are programmatically generating JavaScript source code from JSP.

some_string is a variable name, but not one you've declared, so you get a ReferenceError.

You need to generate the JS source code which gives you the result you need.

For most cases, due to the compatibility between JS and JSON, you can use a JSON stringifier to generate the source code that creates your values (this is a good generic solution as it will do The Right Thing with quotes, new lines, arrays, etc).

Be careful as if the string contains </script> you need to escape the / to prevent it terminating the <script> element. Some JSON serializers will do this by default. I don't know if Java's will.

Upvotes: 1

Related Questions