使用jQuery访问基于Jersey的RESTful服务 [英] Access Jersey based RESTful service using jQuery

查看:91
本文介绍了使用jQuery访问基于Jersey的RESTful服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我使用浏览器访问它,我会得到结果,但是从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.

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

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

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

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?

服务:

@Path("/helloworld")

公共类HelloWorldResource {

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",
            "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:

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:*

"Access-Control-Allow-Origin: *"

新服务如下所示:

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


    @GET
    @Produces
    public Response test(){

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

这篇关于使用jQuery访问基于Jersey的RESTful服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆