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

发布于 2024-11-26 10:38:49 字数 1776 浏览 0 评论 0原文

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

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

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

我可以看到该服务正在发送响应并且它有 200 代码,但我不断从 .ajax 收到错误,没有任何详细信息并且 有什么建议吗?有什么问题吗?

服务:

@Path("/helloworld")

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

高冷爸爸 2024-12-03 10:38:49

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

“Access-Control-Allow-Origin:*”

新服务如下所示:

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


    @GET
    @Produces
    public Response test(){

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

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();
    }
}
我一直都在从未离去 2024-12-03 10:38:49

您必须将 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);
                }
            });
        }

UPDATE

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

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/

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/

裸钻 2024-12-03 10:38:49

如果您使用 JavaScript 函数来替换典型的表单提交,那么请注意您应该返回 false;在你的 javascript 函数的末尾!

您可以在这里检查类似的问题 http://forum.jquery.com/ topic/jquery-newbie-3-9-2011

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文