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?
2 Answers
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.
3 Comments
Pointy
If it's serialized to JSON it can be dropped directly into JavaScript code and used as-is. The JavaScript parser will parse it.
Josh Liptzin
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.
T.J. Crowder
@JoshLiptzin: The array data is clearly coming from a trusted source in this case.
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
T.J. Crowder
It doesn't have to be JSON, it just has to be valid JavaScript. But fundamentally, yeah.
Pointy
.... 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.
Madbreaks
@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.
Madbreaks
@Pointy "the JavaScript parser will do the work" - that is the "additional parsing"
Pointy
@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 :)
|