Jersey + Jsonp + jQuery


At work we are developing an application that required me to create a webservice that could be called from another domain with javascript. Hopefully this will help you do just that. I am using Jersey 1.4 and jQuery 1.4.4.

Here is my Jersey java code for the webservice:

package com.test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.GenericEntity;
import com.sun.jersey.api.json.JSONWithPadding;

@Path("/test")
public class Test {
@GET
	@Path("/jsonp")
	@Produces("application/javascript")
	public JSONWithPadding testJSONP(@QueryParam("jsoncallback") String callback{
		String retVal="YES";
		return new JSONWithPadding(
                              new GenericEntity("{"test":"" + retVal + ""}"){},callback);
	}
}

You can see what gets returned by pasting in the browser
http://localhost:8080/test/jsonp

It should return: callback({“test”:”YES”})

Now to make this call in jQuery:

$.ajax({
    url: 'http://0.0.0.0:8080/test/jsonp', //Sub the 0.0.0.0:8080 to the ip or name of where the webservice is located.
    type: 'GET',
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    success: function(data){
        alert(data.test);
    }
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.