2012-11-11 59 views
2

我使用播放框架2.0.4發佈JSON在play2 AJAX請求

我有一個路線:

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": "[email protected]"}' 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數據,JSON數據爲空時,我執行我的Ajax請求,但通過捲曲好的。

我試圖在我的方法中添加 @ BodyParser.Of(play.mvc.BodyParser.Json.class) ,但它不會改變任何內容。

謝謝你的時間。

回答

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); } 
    });