使用 JQuery Ajax 调用调用 Rest webservice,web 服务返回 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9481073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling Rest webservice using JQuery Ajax call , web service is returning JSON string
提问by Sunny Gupta
I have made a Rest Web Service:
我做了一个 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
}
}
When I go to internet explorer & type this in the address bar:
当我转到 Internet Explorer 并在地址栏中键入以下内容时:
http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2
It is giving me:
它给了我:
{'name':'Peter Norton', 'age':50}
But when I call it using an ajax call in a JQuery method. e.g.
但是当我在 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);
}
});
I am getting an Error in this call.
我在此调用中遇到错误。
When I am debugging using F12 in IE, I am getting following as well
当我在 IE 中使用 F12 进行调试时,我也得到了关注
"Invalid JSON: {\'name\':\'Peter Norton\', \'age\':50}"
Would anybody tell me what could be the problem in my call.
有人能告诉我我的电话可能有什么问题吗?
回答by Validus Oculus
Your service and output is right.
您的服务和输出是正确的。
Problem is same orgin policy http://en.wikipedia.org/wiki/Same_origin_policy
问题是相同的来源政策http://en.wikipedia.org/wiki/Same_origin_policy
Ajax does not allow access to inner level service. For example, in the www.example.com/index.html, you can not access www.example.com/service/book?id=1. Because you changed your context path from www.example.com to www.example.com/service/book. This is not allowed for security but we have one solution
Ajax 不允许访问内部级别的服务。例如,在 www.example.com/index.html 中,您无法访问 www.example.com/service/book?id=1。因为您将上下文路径从 www.example.com 更改为 www.example.com/service/book。出于安全考虑,这是不允许的,但我们有一个解决方案
Previously, I had same problem and I solved it with below code.
I think it can help you.
Key point is dataType: 'json'
以前,我遇到了同样的问题,我用下面的代码解决了它。我认为它可以帮助你。关键是dataType: 'json'
function testService() { $.ajax( { dataType: 'json', headers: { Accept:"application/json", "Access-Control-Allow-Origin": "*" }, type:'GET', url:'http://localhost:8080/service/book/search/1', success: function(data) { document.writeln("Book id : " + data.id); document.writeln("Book title : " + data.name); document.writeln("Description : " + data.description); }, error: function(data) { alert("error"); } }); }
回答by Nicola Peluchetti
I think that you are not returning a valid json: try something like:
我认为您没有返回有效的 json:尝试以下操作:
return "{\"name\":\"unknown\", \"age\":-1}"
because this
因为这
{
"name": "unknown",
"age": -1
}
is a valid JSON (You must use "
, not '
) while this is not
是有效的 JSON(您必须使用"
,而不是'
),而这不是
{
'name': 'unknown',
'age': -1
}
You should also specify the datatype
您还应该指定数据类型
$.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);
}
});
回答by dweeves
use http://jsonlint.com/to validate your output. your quotes are not valid.
使用http://jsonlint.com/验证您的输出。您的报价无效。
{"name":"toto"} is ok
{'name':'toto'} is not