3

我制作了一个 RESTful 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 时,我无法让它工作。

使用海报!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 创建它,但均未成功。

有谁知道我在尝试在 jquery ajax 调用中使用 POST 将 json 发送到 RESTful Web 服务时做错了什么?

4

1 回答 1

0

你试过dataType: 'json'而不是dataType: 'text'在你的ajax调用中吗?

于 2012-09-08T01:32:11.683 回答