0

我正在使用jQuery Datatable插件,我想要獲取在我的控制器操作中發送到服務器的默認參數,如鏈接所示。播放獲取json請求參數

這是我的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: "); 
} 

請求被髮送到服務器,並且操作方法被稱爲體被印刷,但身體。 asJson()和body.asText()總是爲null,如下圖所示。在下面的圖像顯示 enter image description here

而作爲 enter image description here enter image description here

外觀和數據作爲應用程序/ JSON傳遞的要求,這裏糾正我,如果我錯了,那麼爲什麼body.asJson()爲null,如何在操作方法中獲取所有請求參數?我正在使用Play 2.4.2版本(Damiya)。

+1

請參閱'Content-type',它是'x-www-form-urlencoded',它不是JSON。也許你應該使用'body.asFormUrlEncoded()'來代替,請參閱[Default body parser:AnyContent](https://www.playframework.com/documentation/2.4.x/JavaBodyParsers#Default-body-parser:- AnyContent)? –

+0

什麼是接受:application/json? – srk

+0

這是瀏覽器接受的響應,請參閱[接受](http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z3)。 –

回答

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瞭解更多信息。