【问题标题】:Play get json request parameters播放获取json请求参数
【发布时间】:2015-09-29 12:08:25
【问题描述】:

我正在使用jQuery Datatable 插件,我想在我的控制器操作中获取发送到服务器的默认参数,如链接所示。

这是我的ajax请求代码

$(document).ready(function() {
        $('#example').DataTable( {
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "getTable",
                "type": "POST"
            }
        } );
    } );

这是我的控制器操作代码

public Result ajaxDisplayTable() {
        Logger.info("This is just another method for ajax post action call...");
        String userAgent = request().getHeader("User-Agent");
        Logger.info("user agent =  "+ userAgent);
        RequestBody body = request().body();
        Logger.info("bare body = "+ body);
        Logger.info("json ... "+ body.asJson());
        Logger.info("body as json = " + body.asText());
        return ok("Got json: " );
}

请求被发送到服务器并且被调用的动作方法被打印出来,但是 body.asJson() 和 body.asText() 总是为空,如下图所示。

如下图所示

请求参数作为 application/json 传递,在这里纠正我如果我错了,那么为什么 body.asJson() 为 null,如何在 action 方法中获取所有请求参数?我正在使用 Play 2.4.2 版本(Damiya)。

【问题讨论】:

  • Content-type,它是x-www-form-urlencoded,它不是JSON。也许你应该改用body.asFormUrlEncoded(),见Default body parser: AnyContent
  • 接受是什么:application/json?
  • 这是浏览器接受的响应,见Accept

标签: playframework playframework-2.0 datatables playframework-2.4


【解决方案1】:

您的请求以application/x-www-form-url-encoded 发送,请参阅Content-type 标头。您需要使用body.asFormUrlEncoded() 而不是body.asJson()

public Result ajaxDisplayTable() {
    RequestBody body = request().body();
    final Map<String, String[]> values = body.asFormUrlEncoded();
    final String valDraw = values.get("draw")[0];
}

更多信息请参见Body parsers

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2019-03-02
    • 2014-06-27
    • 2019-12-01
    • 1970-01-01
    • 2018-04-26
    • 2011-05-08
    • 1970-01-01
    • 2017-07-17
    相关资源
    最近更新 更多