使用jQuery访问基于Jersey的RESTful服务

Ale*_*lex 4 java jquery jersey

我正在尝试访问RESTful服务,在Java上创建并使用jQuery在Jersey的帮助下部署.

如果我使用浏览器访问它,我会得到结果,但是从jQuery,我收到一个错误,在页面上看不到任何结果.

带有脚本的页面在本地Apache服务器上托管,服务在同一台机器上使用Jersey/Grizzly单独运行.

我可以看到,服务发送的响应,它有200码,但我一直从阿贾克斯得到错误,没有任何细节,任何建议,有什么不好?

服务:

@Path("/helloworld")
Run Code Online (Sandbox Code Playgroud)

公共类HelloWorldResource {

@GET
@Produces
public String test(){
    System.out.println("Sending response");
    return "test";
}
Run Code Online (Sandbox Code Playgroud)

}

主要:

 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",
            "resources");
    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);

}
Run Code Online (Sandbox Code Playgroud)

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);
                }
            });
        }
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 7

经过几天的研究和实验,我发现问题出现在响应的标题中.为了能够使用来自服务的响应,我添加了自定义标头字段:

"Access-Control-Allow-Origin:*"

新服务看起来像这样:

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


    @GET
    @Produces
    public Response test(){

        return Response.ok("test").header("Access-Control-Allow-Origin", "*").build();
    }
}
Run Code Online (Sandbox Code Playgroud)