我得到了
i(k - 1)
奇怪的是,如果我查看firebug中的POST调用,则表示它们不成功,但如果我执行“重新发送”,则会发送它们并检索答案。
我已经在那里尝试了接受的答案:jquery ajax rest call - Unsupported Media Type - 对我不起作用。
-edit:如果有帮助,我会使用Moxy。
Unsupported Media Type - The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
这是我的模特:
var sent = "This is a test request.";
var add = "testing..";
var request = { sentence: sent, addition: add };
$.ajax({
url: "http://localhost:8080/MyProject/Rest/Path/toPost",
type: "POST",
data: JSON.stringify(request),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(resultData) {
//do stuff
},
});
这是我的Servlet:
@XmlRootElement(name = "request")
public class Request {
private String sentence;
private String addition;
public Request() {
this.sentence = "default";
this.addition = "default";
}
public Request(String sentence, String add) {
this.sentence = sentence;
this.addition = add;
}
public String getSentence() {
return sentence;
}
public String getAddition() {
return addition;
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
public void setAddition(String addition) {
this.addition = addition;
}
}
@XmlRootElement(name = "answer")
public class Answer {
private ArrayList<String> lsit;
private String info;
public Answer() {
this.list = new ArrayList<String>();
this.info = "Good";
}
public Answer(ArrayList<String> list, String info) {
this.list = list;
thisinfo = info;
}
public void setInfo(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
public ArrayList<String> getList() {
return list;
}
public void setList(ArrayList<String> list) {
this.list = list;
}
}
答案 0 :(得分:1)
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: "POST",
url: API_URL,
data: JSON.stringify(data),
contentType: 'application/json',
success: resolve,
dataType: 'json'
})
除了使用媒体类型应用程序json的帖子请求之外,这对我们有一个gradle服务器,下面的选项也使用相同的gradle设置
$.ajax({
type: 'POST',
url: API_URL,
contentType: 'application/json',
data: JSON.stringify(data),
complete: resolve
});
答案 1 :(得分:0)
删除charset,因为json不支持charset也将accept设置为json,因为你正在为客户端生成json。
$.ajax({
url: "http://localhost:8080/MyProject/Rest/Path/toPost",
type: "POST",
data: JSON.stringify(request),
Accept : "application/json",
contentType: "application/json",
dataType: "json",
success: function(resultData) {
//do stuff
},
});
答案 2 :(得分:0)
尝试更改此内容:
data: JSON.stringify(request),
到此:
data: request,