ajax - Grails interpreting posted JSON data incorrectly by adding brackets [] to the keys of the object -
i posting data server client side using ajax call. data sent server in form of javascript object, formed this:
var dataobj = { data: rolelist, count: count, units: unitlist }
and posted server via jquery ajax call.
the problem when data received on server, grails adding square brackets keys in data values. example, when print out "params" on server, looks this:
[data[]:[data1, data2, data3], count: 3, units[]:[unit1,unit2]]
whereas should like:
[data:[data1,data2,data3]....]
the problem have these square brackets when try use command object validation of data, data binding cannot take place variable names within command object not include square brackets (and of course can't create variable name in grails include these brackets)
does know why these brackets being added keys in object (when value array , not key itself) , can circumvent problem?
this behaviour doesn't come grails, jquery, see section serialization (tradicional vs. not tradicional , how default changed) in http://api.jquery.com/jquery.param/#entry-longdesc
i still find not documented in jquery, means array parameters brackets appended parameter name (i'm not sure if there other consequences). see example accepted answer this:
what "traditional style of param serialization' in jquery
you can globablly prevent setting tradicional
true
in ajaxsettings
before using jquery.ajax
:
jquery.ajaxsettings.traditional = true;
for example, in application.js have following @ beginning:
if (typeof jquery !== 'undefined') { ... jquery.ajaxsettings.traditional = true; }
another option not send javascript object in form url encoded way, pure json inside body. when doing so, can access parsed json in controller using request.json
, works pretty great data-binding:
browser's console:
jquery.ajax({ type: 'post', url: 'http://localhost:8080/test/jsontest', data: json.stringify({a: 1, b:2}), async: false, contenttype: "application/json; charset=utf-8" }).responsetext
controller:
class testcontroller { def jsontest() { render request.json } }
Comments
Post a Comment