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

我正在尝试访问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 initParams = new HashMap(); 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); } }); } 

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

“Access-Control-Allow-Origin:*”

新服务看起来像这样:

 @Path("/helloworld") public class HelloWorldResource { @GET @Produces public Response test(){ return Response.ok("test").header("Access-Control-Allow-Origin", "*").build(); } } 

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

如果您的服务需要进行身份validation,则可以这样做

 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/

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

你可以在http://forum.jquery.com/topic/jquery-newbie-3-9-2011查看类似的问题

实际上它不是jersey的问题,而是javascript的问题