使用JQuery Ajax调用调用Rest Webservice,Web服务返回JSON字符串
我做了一个Rest Web服务:
package org.jboss.samples.rs.webservices; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/MyRESTApplication") public class HelloWorldResource { @GET() @Produces("application/json") @Path("/dealInfo/{dealId}") public String sayHello(@PathParam("dealId") int dealId) { System.out.println("dealid......"+dealId); switch(dealId) { case 1 :System.out.println("employee id....."); return "{'name':'George Koch', 'age':58}"; case 2: return "{'name':'Peter Norton', 'age':50}"; default: return "{'name':'unknown', 'age':-1}"; } // end of switch } }
当我去Internet Explorer并在地址栏中输入:
http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2
它给了我:
{'name':'Peter Norton', 'age':50}
但是当我在JQuery方法中使用ajax调用来调用它时。 例如
$.ajax({ type: "GET", url: "http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2", data: "", success: function(resp){ // we have the response alert("Server said123:\n '" + resp + "'"); }, error: function(e){ alert('Error121212: ' + e); } });
我在这次通话中遇到错误。
当我在IE中使用F12进行调试时,我也得到了关注
"Invalid JSON: {\'name\':\'Peter Norton\', \'age\':50}"
有人会告诉我在电话中会出现什么问题。
我认为你没有返回一个有效的json:试试类似:
return "{\"name\":\"unknown\", \"age\":-1}"
因为这
{ "name": "unknown", "age": -1 }
是一个有效的JSON(你必须使用"
,而不是'
),而事实并非如此
{ 'name': 'unknown', 'age': -1 }
您还应该指定数据类型
$.ajax({ type: "GET", url: "http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2", dataType: "json", success: function(resp){ // we have the response alert("Server said123:\n '" + resp.name + "'"); }, error: function(e){ alert('Error121212: ' + e); } });
您的服务和输出是正确的。
问题是相同的orgin政策http://en.wikipedia.org/wiki/Same_origin_policy
Ajax不允许访问内部级别的服务。 例如,在www.example.com/index.html中,您无法访问www.example.com/service/book?id=1。 因为您已将上下文路径从www.example.com更改为www.example.com/service/book。 这不是安全性,但我们有一个解决方案
以前,我有同样的问题,我用下面的代码解决了它。 我认为它可以帮到你。 关键点是dataType: 'json'
function testService() { $就( { dataType:'json', 标题:{ 接受: “应用/ JSON”, “Access-Control-Allow-Origin”:“*” }, 键入: 'GET', url: 'HTTP://本地主机:8080 /服务/电子书/搜索/ 1' 成功:function(数据) { document.writeln(“Book id:”+ data.id); document.writeln(“书名:”+ data.name); document.writeln(“Description:”+ data.description); }, 错误:function(数据) { 警报( “错误”); } }); }
使用http://jsonlint.com/validation您的输出。 你的报价无效。
{"name":"toto"} is ok {'name':'toto'} is not