简体   繁体   English

Play Framework 2.1无法处理来自控制器的JSON POST请求

[英]Play Framework 2.1 Cannot handle JSON POST request from controller

I am trying to achieve something simple, using play framework 2.1 (java): 我正在尝试使用播放框架2.1(java)实现一些简单操作:

Post JSON data via jquery, and retrieve it from a controller. 通过jquery发布JSON数据,然后从控制器中检索它。

Could you kindly tell me where I am wrong? 您能告诉我我哪里错了吗?

It starts from a javascript call: 它从javascript调用开始:

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: 数据似乎已正确发布:Firebug控制台:

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 : 如果我打印出request()似乎是空的:

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

Do you see where I am wrong? 看到我错了吗? How could I get the JSON right? 我如何正确获取JSON?

Thanks in advance 提前致谢

I had exactly the same issue. 我有完全一样的问题。 Besides the dataType , you have to set contentType as well, as the original poster suggested: 除了dataType ,还必须设置contentType ,如原始发布者建议的那样:

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请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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