gidoy nyemot
gidoy nyemot

Reputation: 185

Play Framework Cross Domain Web Service

I've been trying to create a Web Service with play framework. I've searched some tutorial and resource about this and end up using the renderJSON() method to provide JSON RESTful web service.

But, there seems to be a problem with that when I try to consume the web service with JQuery. If I use JSON, it fails with this error Origin http://localhost is not allowed by Access-Control-Allow-Origin. Which seems to be a cross-domain problem. Then I try to use JSONP as the datatype when JQuery trying to consume the web service, again there's an parseError problem.

After some research, I found that to provide a web service to the JSONP request. We need to provide something like a callback function. So it's not enough to return only the JSON object to the client. If I'm not mistaken, The format should look something like {#callback-function}{#JSON-data}

How to make a Cross-Domain web service in Play Framework? Is there any workaround for this? Is there anyway to keep the JSON format of a/a list of object to a string instead of render the object as JSON directly as done by calling renderJSON()?

Upvotes: 1

Views: 3155

Answers (2)

benzonico
benzonico

Reputation: 10833

This is working great but you can use Gson object directly instead of the flexjson object.

Upvotes: 0

Anthony Shull
Anthony Shull

Reputation: 1095

Here is what I did. In my routes I set the format of the response to javascript with:

GET /api/projects.json Api.projects(format:'json')

Then for the controller in Api I used flexjson and did this:

public static void projects(String p) {
        JSONSerializer json = new JSONSerializer();
        List<Project> projects = Project.all().fetch(3);
        renderJSON(p + '(' + json.serialize(projects) + ')');
    }

So now jsonp calls can be made by hitting /api/projects.json?p=whatever and the return will be:

whatever([{"your":"json"}])

You can also use flexjson to only serialize the parts of the object that you want to expose.

Testing it with jquery:

$.ajax({
  url: "http://api/projects.json",
  dataType: "jsonp", 
  jsonp : 'p',
  crossDomain : true,
  success: function(data){
   console.log(data);
  }
});

Upvotes: 3

Related Questions