Friday, August 20, 2010

SmartGWT cross domain JSON Data Source

I was struggling to find an XJSON data source example (That is, a data source that is capable of loading JSON from a domain other than where the scripts resides), so battled through it myself.
The example below shows how to do it.

// Create your XJSONDataSource object. Its just a standard data source with a few whistles.

DataSource ds = new XJSONDataSource();
ds.setRecordXPath("/item");

// Set it up with whatever fields you want, as per usual

DataSourceTextField name = new DataSourceTextField("name", "Data Name");
name.setValueXPath("name");

DataSourceIntegerField id = new DataSourceIntegerField("id", "Data Id");
id.setValueXPath("id");
id.setPrimaryKey(true);

ds.setFields(id, name);

// DataSource is now ready for data. Give it a url.

ds.setDataURL("http://your_json_url_feed");

Once this loads (and remember to fetch the data through your tree grid or whatever else is viewing it), it will send a request that looks something like this:

http://your_json_url_feed?callback=isc.Comm._scriptIncludeReply_0

The JSON that your server must send must be wrapped around this callback label. For example:

isc.Comm._scriptIncludeReply_0 ({"item": [ {"id": "1","name": "Monkey"},
{"id": "2","name": "Tree"},
{"id": "3","name": "Banana"} ] })

The callback value can change, so make sure your server code picks it up and puts it in the right place within the response accordingly.

3 comments:

CA said...

First off, Ben thank you so much for this post it saved my life.

Just a couple things that would help clear up the concept in your post:

callback:isc.Comm._scriptIncludeReply_4

is a get parameter in the request:

String callbackString = request.getParameter("callback");

In the response, even those its a X-JSON you will write the response in the body and not as a header:

response.getWriter().write(callbackString + " (" + reportListJson + " )");

Thanks again

OSHI said...

Thank you so much for this post..
But I still have an error when make a request to my json webservice.. I have two project: restlet webservice as a server, and client using smartGWT.. Both project run in localhost n different port. I have an error message: Uncaught JavaScript exception [Script error.] in , line 0. How to solve this error? thx Ben..

jorge luis said...

This is great! I did not try the code itself, but the explanation was good enough so I could implement it in my code. Thanks for posting!