gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:56:56 24 4
gpt4 key购买 nike

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

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

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

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

服务:

@Path("/helloworld")

公共(public)类 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);
}
});
}

最佳答案

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

“访问控制允许来源:*”

新服务如下所示:

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


@GET
@Produces
public Response test(){

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

关于java - 使用 jQuery 访问基于 Jersey 的 RESTful 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6796520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com