简体   繁体   中英

Play Framework 2.1 Cannot handle JSON POST request from controller

I am trying to achieve something simple, using play framework 2.1 (java):

Post JSON data via jquery, and retrieve it from a controller.

Could you kindly tell me where I am wrong?

It starts from a javascript call:

var object = new Object();

object.title = "Hamlet";
object.author = "Bill";

var jsonData = JSON.parse(JSON.stringify(object));
jsRoutes.controllers.Application.update().ajax({
    type : 'POST',
    dataType : 'json',
    data : jsonData,
    success : function(data) {
        // I get the success
    },
    error : function(data) {
        alert('error');
    }
});

The data seems to be correctly posted: Firebug console:

Headers:

Response Headers
Content-Length  2
Content-Type    text/plain; charset=utf-8
Request Headers
Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate

... Parameters

Parametersapplication/x-www-form-urlencoded
title   Hamlet
author  Bill
Source
title=Hamlet&Author=Bill

It routes here:

POST    /update       controllers.Application.update()

Here is the Application Controller:

@BodyParser.Of(BodyParser.Json.class)
public static Result update() {
    JsonNode json = request().body().asJson();

    if(json == null){
        return badRequest("empty json"); // PROBLEM: THE JSON IS ALWAYS NULL
    }
    return ok("{}");
}

And the problem I get is I cannot retrieve my parameters from the request. the request() seems empty if i print it :

DefaultRequestBody(None,None,None,None,None,None,true)

Do you see where I am wrong? How could I get the JSON right?

Thanks in advance

I had exactly the same issue. Besides the dataType , you have to set contentType as well, as the original poster suggested:

var jsonMsg = JSON.stringify(msg);
jsRoutes.controllers.Application.sendJson().ajax({
    type : 'POST',
    dataType : 'json',
    contentType : 'application/json; charset=utf-8',
    data : jsonMsg
});

这可以帮助您本示例演示如何逐步实现Ajax播放播放2.x:如何使用通用按钮发出AJAX请求

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM