Howto get a map from params in Grails Controller?

喜夏-厌秋 提交于 2019-12-08 03:40:03

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/16685146/howto-get-a-map-from-params-in-grails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!