AJAX publishes JSON data from Javascript to Grails

I am trying to format POST JSON data from Javascript (using Prototype) in Grails. My Javascript Code:

var JSONObject = new Object;
    JSONObject.id = "23";
    JSONObject.name = "Test 1";
    JSONstring = JSON.stringify(JSONObject);



 var url = "${createLink(controller:'testController', action:'receiveJson')}";
    new Ajax.Request(url, {
      method:'post',
      contentType:'application/json',
      parameters:JSONstring,
      asynchronous:true,
      onSuccess: function (req) {
        sendInfoResponse(req.responseText);
      }
    });

and my Grails controller code:

def receiveJson = {
  def json = request.JSON;
}

However, in my tests, the 'json' variable seems empty. I would be so grateful if anyone could explain what I am doing wrong. Many thanks.

+3
source share
3 answers

In Ajax.Request parameters change

parameters:JSONstring,

to

postBody:JSONstring,

The problem with using parameters is that the URL encodes the data so that the request body looks like this:

%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=

Instead of what you want (what you get with postBody):

{"id":"23","name":"Test 1"}
+5
source

mfloryan - , .. .

hvgotcodes. , , , , . , request.JSON, {}, request.json, null.

EDIT: "" : request.JSON.toString()

EDIT: . , , , . .

+1

, Ajax.Request. :

" , URL- get . URL-, Hash- ( ), , .

, -

...
parameters: {json: JSONString}
...

request.json

- Prototype, "json", json. .

EDIT - , javascript.

:

var JSONObject = new Object;

-

var JSONObject = new Object();
...

,

var jsonObject = {};
....
0

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


All Articles