1

Im trying to pass an array of strings from a java servlet to a jsp file. now, i want to use that array in a javascript function in that same jsp file. is this possible?

1
  • Not directly. JSP is a server side technology. Javascript is a client side technology. Commented Feb 25, 2014 at 23:14

2 Answers 2

2

You'd have to first serialize it (JSON format is probably easiest) and then deserialize it in javascript to be able to use it as an array.

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

3 Comments

If it's serialized to JSON it can be dropped directly into JavaScript code and used as-is. The JavaScript parser will parse it.
You may still want to use JSON.parse(<string>) rather than dropping <string> directly into Javascript source code (depending on where <string> comes from) to be able to catch JSON decode exceptions and defend against potential security issues.
@JoshLiptzin: The array data is clearly coming from a trusted source in this case.
1

Yes, you'll need to convert the array to JSON first though, then have your JavaScript function parse that JSON. At that point it can work with it as a standard JS array (because at that point, it is).

EDIT - I did not mean to imply that JSON is absolutely required, nor that it is the only possible solution. It's simply an option, and in my opinion probably the best and easiest for what you're trying to accomplish.

8 Comments

It doesn't have to be JSON, it just has to be valid JavaScript. But fundamentally, yeah.
.... and there's no need for additional parsing - the JavaScript parser will do the work and the code will have a ready-to-use native JavaScript array.
@T.J.Crowder What would you suggest, as far as a better approach than using JSON? Because I fully agree, but I can't think of a better/easier/more efficient approach than using JSON. If you can, please provide an answer. If not, I don't think the pedantic nit picking really helps here. No offense.
@Pointy "the JavaScript parser will do the work" - that is the "additional parsing"
@Madbreaks yes, I'm not disagreeing with you. I've seen code that involves stuff serialized to JSON and then string-escaped and dropped into a JavaScript string. That's the sort of crazy stuff we need to avoid in this troubled world :)
|

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.