Pergunta

I'm trying to retrieve in the controller a complex object sent from the client (via ajax) in JSON format, but I don't know how to get from params the map in which are converted some of the properties.

For example, imagine this is the "complex" JSON object (the number of items in the meta object is variable, could be one, two, three... and with variable names):

{ 
  language: "java",
  meta: {
      category: "category1"
  }
}

When this object is sent via jQuery, in the controller I get this in params object:

[language:java, meta[category]:category1, action: register, controller: myController]

And this is how I send the object via jQuery. I have a common function for several calls:

if (!params) params = {};

var url = this.urls.base+"/"+controller+"/"+action+"?callback=?";
if (params.callback)
    url = this.urls.base+"/"+controller+"/"+action+"?callback="+params.callback;
url = url + "&_"+new Date();
delete params.callback;
$.ajax({
    url: url,
    data: params,
    crossDomain:true,
    dataType:'jsonp',
    cache:false,
    ajaxOptions: {cache: false},
    jsonp: params.callback?false:true
});

and in params for the ajax call I send for testing the JSON object that i wrote before

If I try to do params.meta in the controller, I get a null object. How I'm I supposed to retrieve the map from the params object?

Foi útil?

Solução

On client side you have to send data using POST method, and configure jQuery to send it as JSON. Like:

data = { 
  language: "java",
  meta: {
      category: "category1"
  }
}
$.ajax({
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json',
})

And get on server side as request.JSON see docs: http://grails.org/doc/2.2.0/ref/Servlet%20API/request.html

But, if you need to make Cross Domain request, POST method just doesn't work. At this case you can pass your complex object as a parameter, and parse on server from the string. Like:

$.ajax({
  data: {myjson: JSON.stringify(data)}
})

and:

def myjson = JSON.parse(params.myjson)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top