Send Json message with ajax and Play Framework 2

I have a problem sending json data to Play Controller.

seach.scala.html

$.ajax({ type : "POST", dataType: 'json', data: { 'filter': "John Portella" }, url : "@routes.Search.findPag()", success: function(data){ console.log(data); } }); return false; 

Controller: POST /find/findPag Search.findPag()

 public static Result findPag(){ JsonNode json = request().body().asJson(); return ok(); } 

Debugging I get json = null. What do you think is the problem? Thanks.

+4
source share
2 answers

You need to complete the data line . As of now, I think .toString() will be called on the data object, and this is not something that can be correctly parsed as JSON on the server side.

 var d = { 'filter': "John Portella" }; $.ajax({ type : "POST", dataType: 'json', data: JSON.stringify(d), url : "@routes.Search.findPag()", success: function(data){ console.log(data); } }); 
+7
source

You will have to "contentType" the data.

  var d = { 'filter': "John Portella" }; $.ajax({ type : "POST", dataType: 'json', data: JSON.stringify(d), contentType: "application/json; charset=utf-8", url : "@routes.Search.findPag()", success: function(data){ console.log(data); } }); 
+1
source

Source: https://habr.com/ru/post/1479451/


All Articles