开发者

Access Jersey based RESTful service using jQuery

I am trying to access RESTful service, created on Java and deployed with help of Jersey using jQuery.

If I access it using browser I will get the result, but from jQuery, I am getting an error and can not see any results on the page.

Page with the script is hosting on local Apache server and the Service is running separately using Jersey/Grizzly on the same machine.

I can see that service is sending the response and it has 200 code, but I keep getting error from .ajax, without any details and Any suggestions what is wrong?

Service:

@Path("/helloworld")

public class HelloWorldResource {

@GET
@Produces
public String test(){
    System.out.println("Sending response");
    return "test";
}

}

Main:

 public static void main(String[] args) throws IOException {

    final String baseUri = "http://localhost:9998/";
    final Map<String, String> initParams = new HashMap<String, String>();
    initParams.put("com.sun.jersey.config.property.packages",
            "re开发者_高级运维sources");
    System.out.println("Starting grizly");
    SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);

    System.out.println(String.format(
            "Jersey app started with WADL available at %sapplication.wadl\n"
            + "Try out %shelloworld\nHit enter to stop it...", baseUri, baseUri));
    System.in.read();
    threadSelector.stopEndpoint();
    System.exit(0);

}

JavaScript:

var serviceAddress = "http://192.168.1.2:9998/helloworld";
        function loadDeviceData(){
            $.ajax({
                DataType: "text",
                url: serviceAddress,
                success: function (data) {
                    alert("Data loaded: " + data);
                },
                error: function (xhr) {
                    alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
                }
            });
        }


After a couple of days of research and experiments I discovered that the problem was in the headers of the response. To be able to use the response from the service, I added custom header field:

"Access-Control-Allow-Origin: *"

New service looks like this:

@Path("/helloworld")
public class HelloWorldResource {


    @GET
    @Produces
    public Response test(){

        return Response.ok("test").header("Access-Control-Allow-Origin", "*").build();
    }
}


you have to set crossDomain to true to make cross domain requests

var serviceAddress = "http://192.168.1.2:9998/helloworld";
        function loadDeviceData(){
            $.ajax({
                dataType:'html',
                type:'GET',
                crossDomain:true,
                cache:false,
                async:false,                    
                url: serviceAddress,
                success: function (data) {
                    alert("Data loaded: " + data);
                },
                error: function (xhr) {
                    alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
                }
            });
        }

UPDATE

if your service required the authentication may be you can do it like this

var serviceAddress = "http://192.168.1.2:9998/helloworld";
            function loadDeviceData(){
                $.ajax({
                    dataType:'html',
                    type:'GET',
                    crossDomain:true,
                    cache:false,
                    async:false,
                    xhrFields: {
                      withCredentials: true
                    },
                    username:'yourUsername', //not sure about the username and password options but you can try with or without them
                    password:'thePass',                    
                    url: serviceAddress,
                    success: function (data) {
                        alert("Data loaded: " + data);
                    },
                    error: function (xhr) {
                        alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
                    }
                });
            }

also use jquery 1.5.1 or higher because the crossDomain and some other options are not available in the earlier versions. For reference see this link http://api.jquery.com/jQuery.ajax/


if you are using a javascript function to replace a typical form submission then pay attention to the fact that you should return false; at the end of your javascript function!

you can check a similar issue here http://forum.jquery.com/topic/jquery-newbie-3-9-2011

actually it is nota a matter of jersey but a matter of javascript

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜