Hi Friends,
Lets discuss today about sending JSON objects with ajax request using JQuery. We have number of functions in jQuery to kick-off an ajax request. But for sending JSON objects along with the request, I chose jQuer.ajax(). It takes various parameters url, type, data, dataType, beforeSend etc. Its API can be found here.
Lets look at example given below:
jQuery.ajax({ url: <Url of the action>, type: "POST", data: {name: "amit", id:1 }, dataType: "json", beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { //Write your code here } });
The above example works for simple JSON object. Now lets see how we can send JSON objects list as given below:
var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3, name:"atin"},{id:1, name:"puneet"}]; jQuery.ajax({ url: <Url of the action>, type: "POST", data: {students: JSON.stringify(jsonObjects) }, dataType: "json", beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { //Write your code here } });
If you notice, for sending my json objects it has not been written directly as data: jsonObjects. As it expects the JSON object passed to it written as key value pair. So we made students the key. And since we have json objects stored in a variable, we need to expand the json objects list using stringify(), otherwise it would be sent as a java script object.
Now on the server we can parse the JSON object, and use it as the list of objects of type map. For example
//this code is written in grails import grails.converters.JSON; List<JSON> students = JSON.parse(params.students) //students in request params is parsed to json objects and stored in the List println "Student id: " + students[0].studentId //first element of the students list is accessed as a map holding a key studentId
Hope this helpled!
~~Amit Jain~~
amit@intelligrape.com
http://www.IntelliGrape.com
