我正在使用play framework 2.0.4
我有一条路线:
POST / addMail controllers.Application.addMail()
在我的控制器应用程序中,我定义了addMail方法:
public static Result addMail()
{
JsonNode json = request().body().asJson();
Long id = json.findPath("id").asLong(0);
String email = json.findPath("email").getTextValue();
GameScore gs = GameScore.findById(id);
gs.setEmail(email);
gs.save();
return ok();
}
如果我通过CURL调用此方法,我没有问题:
curl --header "Content-type: application/json" --request POST --data '{"id": 13, "email": "test@DB.com"}' http://localhost:9000/addMail
但如果我通过AJX请求调用此方法,我会得到500响应。
$addMailBtn.click(function(event) {
$this = $(this);
var id = $this.attr("id").substring(14);
var email = $("#saisieMailField_" + id).val();
$.ajax({
type: 'POST',
url: "@routes.Application.addMail()",
dataType:"json",
data: {"id":id, "email": '"' + email + '"'},
success: location.reload()
})
} );
如果我在我的控制台中打印我的json数据,当我执行我的ajax请求时json数据为空,但是通过curl可以正常。
我试图添加 @ BodyParser.Of(play.mvc.BodyParser.Json.class) 在我的方法上但它没有改变任何东西。
感谢您的时间。
答案 0 :(得分:1)
这对我有用。请注意,我将JSON对象字符串化,我认为这是你的问题。
$.ajax({
type: "POST",
url: "http://myservice:9000/api/v1/positions",
data: JSON.stringify({"nwLng":72.22,"nwLat":22.22, "seLng":22.22,"seLat":55.33}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data); },
failure: function (errMsg) { alert(errMsg); }
});