我抬起头,在论坛上类似的错误,但似乎无法正常工作还是和我得到 Status Code: HTTP/1.1 415 Unsupported Media Type
发送JSON通jQuery的POST不打REST服务
我送这个jQuery:
$("#btnInsertCustomer").click(function(){
var myObj = {name: "Bill Adama", address:"Vancouver Canada"};
var jsondata = JSON.stringify(myObj);
$.ajax({
type: "POST",
url: "http://localhost:8081/RestDemo/services/customers/add",
contentType: "application/json",
dataType: "json",
data: jsondata,
success: function (resp, status, xhr) {
var msg = "Name: " + resp.name + ", Address: " + resp.address;
alert(msg);
$("#successPost").html(msg + " - STATUS: " + xhr.status + " " + xhr.statusText);
},
error: function(resp, status, xhr){
alert("Error: " + resp.e);
$("#errorPost").html("Error: " + resp.e + " - STATUS: " + xhr.status + " " + xhr.statusText);
}
});
});
此以下资源:
@POST
@Path("/add")
@Produces("application/json")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public String addCustomer(Customer customer) {
//insert
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
//get inserted
Customer result = customerMap.get(id);
return "{\"name\": \" " + result.getName() + " \", \"address\": \"" + result.getAddress() + "\"}";
}
它没有击中中的service,并给我的错误。我无法理解,如果错误是格式化发送数据在jQuery端(这似乎是好的)或在服务接收器。
任何帮助表示赞赏,谢谢!
更新1:创建一个DTO移转给
$("#btnInsertCustomer").click(function(){
//var myObj = '{"name": "Bill Adama", "address":"Vancouver Canada"}';
//var jsondata = JSON.stringify(myObj);
var NewCustomer = { };
NewCustomer.name = "Bill Adama";
NewCustomer.address = "Vancouver Canada";
var DTO = { 'NewCustomer' : NewCustomer };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:8081/RestDemo/services/customers/add",
data: JSON.stringify(DTO),
dataType: "json",
success: function (resp, status, xhr) {
var msg = "Name: " + resp.name + ", Address: " + resp.address;
alert(msg);
$("#successPost").html(msg + " - STATUS: " + xhr.status + " " + xhr.statusText);
},
error: function(resp, status, xhr){
alert("Error: " + resp.e);
$("#errorPost").html(resp.e + " - STATUS: " + xhr.status + " " + xhr.statusText);
}
});
});
,但我仍然得到同样的错误!
即使这种方式实际上新台币创下了Web服务的brakpoint ......而搞定不做工精细。 – mzereba 2012-08-01 11:05:11
用海报(Firefox)测试这个结果给出了同样的错误...显然问题出在Resource类中接受json。任何人都可以帮忙吗? – mzereba 2012-08-01 12:02:57