How to pass an array of objects from javascript to Java
Hello Im trying to pass an array of objects from javascript to java , but how can this be done..?? I've found in some posts that they do this using a hidden input. Is this the only way? I'm a bit confused. Please tell me what do I need to 开发者_如何学Cdo to pass my array to the server? and which javascript files and jars do I need to add?
Thanks in advance.
You seem to want a completely baked-in solution. Not sure I can provide that, but here's what I'd do.
Indeed use a hidden input field in a form, where the value of the field is a valid JSON string. Send the form to your server, and in your servlet use a JSON Java library to parse the JSON string.
Here json-lib, gson or Jackson would do. In your case, I'd say json-lib would seem the easiest to use.
To generate the JSON string on the client-side, either use a framework or custom solution. For instance, jQuery has a serialize() function to serialize a form's fields to a JSON object directly, which you can then convert to string. Other frameworks provide similar functions.
To learn more about JSON, be sure to read the JSON Wikipedia entry and to visit the official JSON page (which also gives you a Java implementation of the JSON data-interchange format, though maybe not the most efficient one for processing a lot of data). To make sure your generated JSON is valid, you can use JSONLint.
If the objects are simple enough, you can encode your array as a JSON string. Java has libraries to encode and decode JSON.
精彩评论