I want to build a web service that is able to send back a JSONP
My service looks like the following
@GET
@Path("user/{id}")
@Produces({"application/javascript", MediaType.APPLICATION_JSON})
@JSONP(callback= "eval",queryParam = "callback")
public Response getUser(@PathParam("id") int id, @Context HttpHeaders headers
) {
//for (MediaType mediaType : headers.getAcceptableMediaTypes()) {
// System.out.println(mediaType);
//}
User u = UserDao.instance.getModel().get(Integer.toString(id));
Response res = Response.status(Response.Status.OK).entity(u).build();
return res;
}
Is it right? or wrong?
when I access the service with Jquery (I'm a newbie to jquery atm) I get an error, the following is the code that I use to access the service.
jQuery.ajax({
type: "GET",
url: "http://localhost:8084/simple-service/webapi/myresource/user/1",
dataType: "jsonp",
success: function(results) {
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
}
});
Am I doing something wrong here? I have two different error messages:
{"id":"1","name":"Brittni","surname":"North"}
It looks like is missing the name of the callback fucntion? :S
Can you help me spotting out what I am doing wrong? :D thanks for helping!
ok guys! I solved it by my self, here is the solution if you are interested at it.
Here is the code of the service if you want to reach it when you are not in the same origin:
set the headers over the response, additionally add the @Jsonp
annotation.
@GET
@Path("user/{id}")
@Produces({"application/javascript", MediaType.APPLICATION_JSON})
@JSONP(callback= JSONP.DEFAULT_CALLBACK,queryParam = JSONP.DEFAULT_QUERY)
public Response getUser(@PathParam("id") int id, @Context HttpHeaders headers
) {
User u = UserDao.instance.getModel().get(Integer.toString(id));
Response res = Response.status(Response.Status.OK).entity(u).build();
res.getHeaders().add("Access-Control-Allow-Origin", "*");
res.getHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
res.getHeaders().add("Access-Control-Allow-Credentials",
"true");
res.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
return res;
}
For Cross-domain call, use the built in flags in the ajax request. The other fields (like dataType) will be automagically filled by jquery in a smart fashion.
jQuery.ajax({
type: "GET",
url: "http://localhost:8084/simple-service/webapi/myresource/user/" + e.data.id,
crossDomain: true,
success: function(results) {
console.log("Success!");
$this.trigger("populate", [results]);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
}
});