2012-07-05 100 views
3

我制作了一个REST风格的Web服务。尝试使用jquery ajax和jersey将jQuery发布为REST风格的Web服务

@POST 
@Path("/test") 
@Consumes({ MediaType.APPLICATION_JSON}) 
public String test(TestObject to) 
{ 
    System.out.println(to.getTestString()); 
    return "SUCCESS"; 
} 

我与@XmlRootElement

@XmlRootElement 
public class TestObject implements Serializable { 
    private static final long serialVersionUID = 1L; 

    private String testString; 

    public TestObject() {} 

    public TestObject(String testString) { 
     this.testString = testString; 
    } 

    public String getTestString() { 
     return testString; 
    } 
    public void setTestString(String testString) { 
     this.testString = testString; 
    } 
} 

然后我尝试用下面的Ajax调用

$.ajax({ 
    url: 'http://localhost:8080/testPage/test/', 
    type: 'POST', 
    data: '{"testString":"test"}', 
    dataType: 'text', 
    contentType: "application/json; charset=utf-8", 
    success: function(jqXHR, textStatus, errorThrown){ 
     alert('Success'); 
    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
     alert("jqXHR - " + jqXHR.statusText + "\n" + 
       "textStatus - " + textStatus + "\n" + 
       "errorThrown - " + errorThrown); 
    } 
}); 

我最终得到简单的“错误”回调用它创建的对象为textStatus。它似乎甚至没有达到我的测试服务。当我只通过文本/平原时,我将获得GET工作,甚至POST工作。当我尝试传递一个json时,我无法启动它。

使用POSTER! Firefox附加组件我能够成功地调用传递相同数据的服务。我添加了一些额外的日志记录来捕获服务端的请求头,所以它似乎至少看到请求,但它没有做任何事情。

以下是我从日志中获得的请求。最重要的一个是失败的ajax。最后一个是成功使用POSTER的。 (不是真正的代码,但我看不出有什么更好的把它放在)

INFO: 1 * Server in-bound request 
1 > OPTIONS http://localhost:8080/testPage/test 
1 > Host: localhost:8080 
1 > User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1 
1 > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
1 > Accept-Language: en-us,en;q=0.5 
1 > Accept-Encoding: gzip, deflate 
1 > DNT: 1 
1 > Connection: keep-alive 
1 > Origin: http://localhost:8081 
1 > Access-Control-Request-Method: POST 
1 > Access-Control-Request-Headers: content-type 
1 > Pragma: no-cache 
1 > Cache-Control: no-cache 
1 > 

INFO: 2 * Server in-bound request 
2 > POST http://localhost:8080/testPage/test 
2 > Host: localhost:8080 
2 > User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1 
2 > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
2 > Accept-Language: en-us,en;q=0.5 
2 > Accept-Encoding: gzip, deflate 
2 > DNT: 1 
2 > Connection: keep-alive 
2 > Content-Type: application/json; charset=utf-8 
2 > Content-Length: 22 
2 > Cookie: JSESSIONID=bvizai6k0277 
2 > Pragma: no-cache 
2 > Cache-Control: no-cache 
2 > 
{"testString": "test"} 

从这个似乎是不获取传递给服务的JSON。我已经试过如上写出JSON,我试图使用JSON.stringify来创建它既不成功。

有没有人知道我做错了,当试图发送一个JSON到一个REST风格的Web服务使用POST在jQuery的Ajax调用?

+0

你得到的解决方案我也面临类似的问题http://stackoverflow.com/questions/15094620/unable-to-make-cors-post-request-in-javascript-to-java-web-servicejersey – 2013-02-27 06:00:04

回答

0

您是否在您的ajax调用中尝试使用dataType: 'json'而不是dataType: 'text'

相关问题