简体   繁体   中英

Jquery Ajax call to Rest service error

I have made a Rest Web Service:

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;
  }
} 

When I go to internet explorer & type this in the address bar:

http://localhost:8080/LondonAirQuality.Rest/rest/todo/

It is giving me:

{"description":"This is my first todo","summary":"This is my first todo"}

But when I call it using an ajax call in a JQuery method. eg

$.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);
  }
});

I am getting an Error in this call, but in Firebug I see request is 200 OK and in the response the correct json. 在此处输入图片说明 Anyone can help me?

The problem was the "same origin policy" and the solution have been to add the class ResponseCorsFilter to the server:

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;
}

}

And add an init-param to Jersey 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>

Thanks. I hope this can help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM