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

时间:2011-07-22 21:54:17

标签: java jquery jersey

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

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

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

我可以看到服务正在发送响应并且它有200个代码,但我不断收到.ajax的错误,没有任何细节和 有什么建议是错的吗?

服务:

@Path("/helloworld")

公共类HelloWorldResource {

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

}

主:

 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);

}

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);
                }
            });
        }

3 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:0)

您必须将crossDomain设置为true才能生成跨域请求

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);
                }
            });
        }

<强>更新

如果您的服务需要身份验证,则可以这样做

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);
                    }
                });
            }

也使用jquery 1.5.1或更高版本,因为crossDomain和其他一些选项在早期版本中不可用。有关参考,请参阅此链接http://api.jquery.com/jQuery.ajax/

答案 2 :(得分:0)

如果您使用javascript函数替换典型的表单提交,请注意您应该返回false;在你的javascript函数结束时!

您可以在http://forum.jquery.com/topic/jquery-newbie-3-9-2011

查看类似问题

实际上这不是球衣的问题,而是javascript的问题