Jquery Ajax调用Rest服务错误
我制作了一个Rest Web服务:Jquery Ajax调用Rest服务错误,jquery,ajax,json,rest,Jquery,Ajax,Json,Rest,我制作了一个Rest Web服务: import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/todo") public class TodoResource { @GET @Produces({MediaType.APPLICATION_JSON}) public Todo getXML() {
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/todo")
public class TodoResource {
@GET
@Produces({MediaType.APPLICATION_JSON})
public Todo getXML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
@GET
@Produces({ MediaType.TEXT_XML })
public Todo getHTML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
}
当我转到internet explorer并在地址栏中键入以下内容时:
http://localhost:8080/LondonAirQuality.Rest/rest/todo/
它给了我:
{"description":"This is my first todo","summary":"This is my first todo"}
但是当我在JQuery方法中使用ajax调用它时。e、 g
$.ajax({
type: "GET",
url: "http://localhost:8080/LondonAirQuality.Rest/rest/todo/",
dataType: "json",
success: function(data) {
alert('OK : ' + data);
},
error: function (e) {
alert('KO: '+ e.text);
console.log(e);
alert("Status is: " + e.statusText);
}
});
我在这个调用中得到一个错误,但在Firebug中我看到请求是200 OK,在响应中是正确的json。
有人能帮我吗 问题在于“同源策略”,解决方案是将类ResponseCorsFilter添加到服务器:
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
public class ResponseCorsFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {
ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
resp.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
String reqHead = req.getHeaderValue("Access-Control-Request-Headers");
if(null != reqHead && !reqHead.equals("")){
resp.header("Access-Control-Allow-Headers", reqHead);
}
contResp.setResponse(resp.build());
return contResp;
}
}
并将init参数添加到Servlet:
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>de.vogella.jersey.jaxb.security.ResponseCorsFilter</param-value>
</init-param>
com.sun.jersey.spi.container.ContainerResponseFilters
de.vogella.jersey.jaxb.security.ResponseCorsFilter
谢谢。我希望这能帮助一些人。您确定FireBug中的请求属于jQuery调用,而不是URL中的调用吗?你能试着用
done()
和fail()
代替error
和success
吗?是的,我确信这一点。我在不同的标签上打电话。如果我使用“完成”和“失败”而不是“错误”和“成功”,则输出不会通过其中任何一个。您尝试过“完成”和“失败”吗?如果我使用“完成”和“失败”而不是“错误”和“成功”,则输出不会通过任何一个。问题解决了。