$.ajax : how to parse data sent to the controller

368 views
Skip to first unread message

Vineet

unread,
Feb 21, 2012, 4:36:59 AM2/21/12
to web2py-users
Earlier i was using ajax() function.
But since it is not possible to send js array or json object, I am
trying $.ajax function.

--- View ---
var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3,
name:"atin"},{id:1, name:"puneet"}];

$.ajax({
url: "{{=URL('myControllerName')}}",
type: "POST",
context: document.body,
data: {students: JSON.stringify(jsonObjects) },
dataType: "json",
success: function(){
alert('ok');
}
});

--- end View ---

In controller, how do I access the data?

Somebody has give the code for grails as :---

//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

In web2py, how to port this code?

Thanks,

Vineet

Wikus van de Merwe

unread,
Feb 21, 2012, 6:17:44 AM2/21/12
to web...@googlegroups.com
if "students" in request.vars:
  students = json.loads(request.vars.students)
  print students[0]["student_id"]

For python 2.5 you might need to import the simplejson from contrib (I'm not sure if this is done automatically):
import gluon.contrib.simplejson as json

Vineet

unread,
Feb 21, 2012, 6:32:32 AM2/21/12
to web2py-users
Oh I see.
It worked as per your tip.
Thank you !
:)

-- Vineet


On Feb 21, 4:17 pm, Wikus van de Merwe <dupakrop...@googlemail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages