views:

53

answers:

3

I want to create a dictionary containing array and send it to GAE using jquery's ajax request. something like- {'a':'text', 'b':'othertext','c':['texta','textb']} which I'm creating manually. I am able to receive and process a and b using self.request.get on GAE but not the c.

Is there any other way to create JSON object in js? Please suggest whats wrong in this method.

+2  A: 

Presumably, GAE's self.request.get is not able to serialize a complex object like a string array into a GET request format (?a=text&b=othertext...).

One workaround, although perhaps not a very neat one, would be to serialize the value to JSON yourself, and pass that:

var jsonObj = {
               'a':'text', 
               'b':'othertext', 
               'cJSON': JSON.stringify(['texta', 'textb'])
              };

... and then of course you'd have to deserialize cJSON at the receiving end.

David Hedlund
This worked great!!! Thanks David
Cool
+4  A: 

You're not really sending JSON to the server. When you pass the object to jQuery.ajax (or the get/post wrappers), it will be serialized into GET or POST variables, not sent as JSON, so your object would be converted into something like this:

a=text&b=othertext&c[]=texta&c[]=textb

If you want to pass the entire object as JSON, you can convert it yourself by calling JSON.stringify (you will need to include json2.js for browsers that don't support the JSON object natively). Then you can wrap the JSON-encoded string in a map with whatever name you want:

jQuery.post(url, { json: JSON.stringify({a:'text', ...}) }, ...);

On the server side, you can access the JSON text by calling self.request.get("json"). Then you would have to parse the JSON string to extract the values. I don't know much about Python, but apparently you just need to import django.utils.simplejson and call simplejson.loads(json).

Matthew Crumley
I understood what you meant but Davids solution worked for me, +1 for your detailed ans. I really appreciate your help.
Cool
+1  A: 

You're actually sending urlencoded request parameters, not JSON. JQuery is probably encoding the list as multiple values for the same parameter, which means you can access it using self.request.get_all, which will return a list - self.request.get will only return the first value.

Nick Johnson
Hi Nick, I tried get_all, but It was not working when I was sending 'c':['texta','textb']
Cool
@Cool: Not that this matters since you got it working already, but `get_all` would probably work if you call it like this: `self.request.get_all("c[]")`. By default, jQuery uses PHP's convention of puting '[]' at the end to treat the parameter as an array.
Matthew Crumley