Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle java object in javascript

I am using Ajax in my JavaScript and that sets an array of objects of following class in a response:

public class RetrieveTempSecVersions {

    private String templateName;
    private int[] versionNumber;

    public String getTemplateName() {
        return templateName;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

    public int[] getVersionNumber() {
        return versionNumber;
    }

    public void setVersionNumber(int[] i) {
        this.versionNumber = i;
    }
}

using:

aoRes.setContentType("text/xml");
aoRes.setHeader("Cache-Control", "no-cache");
aoRes.getWriter().write(template[]);

Now I want to read all the elements from template array and its details into my JavaScript.

Can anyone help me in how to do that?

like image 239
Varun Avatar asked Feb 25 '11 08:02

Varun


People also ask

How objects are handled in JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

Can you run Java in JavaScript?

Other Similar Java JVMDoppio – is a Java JVM that can run Java in a JavaScript engine. It is written in CoffeeScript. This is the one that claims to have the most support for features.

How do you call an object in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

How do I access nested objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };


2 Answers

Have you considered using Google Web Toolkit? With GWT you have a number of choices for sending objects between client and server, including GWT RPC, RequestFactory, and JSON.

like image 166
Isaac Truett Avatar answered Sep 28 '22 05:09

Isaac Truett


You need to transform your array of Java objects into something JavaScript understands. There are two obvious choices : XML (AJAX means Asynchronous Javascript And XML), or JSON. JSON is probably easier and more lightweight.

All the AJAX JavaScript libraries (JQuery, etc.) have good support for JSON. See http://api.jquery.com/jQuery.getJSON/ for example.

There are also several Java APIs to transform Java objects into JSON (look at GSON for example).

You'll have to modify the content type of the response : it's not text/html, but application/json if you use JSON.

like image 32
JB Nizet Avatar answered Sep 28 '22 05:09

JB Nizet