簡體   English   中英

jQuery Ajax調用Rest服務錯誤

[英]Jquery Ajax call to Rest service error

我做了一個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;
  }
} 

當我轉到Internet Explorer並在地址欄中輸入以下內容時:

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

它給了我:

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

但是當我在JQuery方法中使用ajax調用進行調用時。 例如

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

}

並向Jersey Servlet添加一個init-param:

<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>de.vogella.jersey.jaxb.security.ResponseCorsFilter</param-value>
</init-param>

謝謝。 我希望這可以幫助某人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM