Ajax and json

3 views
Skip to first unread message

Frédéric

unread,
Dec 21, 2009, 6:55:10 AM12/21/09
to prototype-s...@googlegroups.com
Hi,

I'm making some tests with AJAX request to retreive json datas.

I tried this example code:

new Ajax.Request('/exec.py', {
method: 'get',
onSuccess: function(transport, json) {
alert(json ? Object.inspect(json) : "no JSON object");
}
});

My request is made on a mod_python page, which returns the json data:

records = Adherent.selectBy(adherent='Oui') # SQLObject request
req.content_type = "application/json"
data = [{'num': record.num,
'prenom': record.prenom,
'nom': record.nom} for record in records]
req.write(simplejson.dumps(data))
return ""

But it does not work: the json var doesn't contain any valid json data...

What am I doing wrong? Is the content_type correct? I found on different
forums that this is the one to use for json, but Prototype may need another
one? I also tried:

application/x-json
text/x-json

without success.

Thanks,

--
Frédéric

T.J. Crowder

unread,
Dec 21, 2009, 8:05:36 AM12/21/09
to Prototype & script.aculo.us
Hi,

> What am I doing wrong?

You're just looking in the wrong place. The second parameter to the
onSuccess callback is the value of the X-JSON *header*, if any. It's a
means of sending back extra data alongside the main response. You're
sending JSON back in the body, not a header. To access that, just look
at the `responseJSON` property of the response object (the first
parameter to the onSuccess). E.g.:

new Ajax.Request(url, {
onSuccess: function(response) {
// The decoded JSON data is available from
// the response.responseJSON property.
}
});

([OT] You've called your first parameter "transport", probably because
you've seen that in examples from a long time back. It's not the
transport, it's an Ajax.Response object. And yes, the docs are wrong;
I've filed a ticket in Lighthouse about that.)

HTH,
--
T.J. Crowder
Independent Software Consultant
tj / crowder software / com
www.crowdersoftware.com

Frédéric

unread,
Dec 21, 2009, 8:32:10 AM12/21/09
to prototype-s...@googlegroups.com
Le lundi 21 décembre 2009 13:05, T.J. Crowder a écrit :

> You're just looking in the wrong place. The second parameter to the
> onSuccess callback is the value of the X-JSON *header*, if any. It's a
> means of sending back extra data alongside the main response. You're
> sending JSON back in the body, not a header. To access that, just look
> at the `responseJSON` property of the response object (the first
> parameter to the onSuccess). E.g.:
>
>     new Ajax.Request(url, {
>         onSuccess: function(response) {
>             // The decoded JSON data is available from
>             // the response.responseJSON property.
>         }
>     });

Ok, I got it. Thanks :o)

--
Frédéric

Reply all
Reply to author
Forward
0 new messages