MrCooL
MrCooL

Reputation: 926

jQuery Post With Data Returned (json, xml etc) with Google App Engine (Python)

I've done jQuery post successfully. However, in order to get the data returned from server side. Can anyone gives example how this can be done in Google App Engine (Python) using webapp framework?

If possible, I need example:

  1. How we can send json data to template.
  2. From template, how we can access the json after jQuery post success function.
  3. I would appreciate very very much if anyone could post it to http://jsfiddle.net

Upvotes: 2

Views: 829

Answers (3)

MrCooL
MrCooL

Reputation: 926

I was actually looking for an answer how to get back the Json object from server side to the jQuery ajax post that I've written. So, here I figured out what went wrong from my earlier solution:

Hence, the solution was simply:

$.post("POST_URL", $("#form").serialize(),
        function(data){
             alert(data); //data returned from server side
        }, "json");

So, 2 mistakes I did:

  1. So, earlier the last parameter "json' was abandoned.
  2. After import django.utils.simplejson as json, I did one silly careless mistake where I used simplejson.dumps instead of json.dumps. (Basically, the wrong variable)

Upvotes: 1

Alvin K.
Alvin K.

Reputation: 4379

JSON made easy:

  1. data_json = [] create an empty array
  2. data_json.append({ 'data1': first-item, 'data2': second-item, ...}) - append as many data as you need
  3. output = json.dumps(data_json) create the json ouput
  4. self.response.out.write(output)

To avoid cross domain issues, you will need to pad the output (known as JSON/P) with a callback function. padded_output = callback_fn + "(" + output + ")" where callback_fn is the callback function sent by the user (usually generated by jQuery).

Upvotes: 2

yati sagade
yati sagade

Reputation: 1375

First of all get to know the json module. The native json module won't work on appengine, so do

import django.utils.simplejson as json

Then, format your to be "json" object(s) as Python dicts,

obj = {"name": "foo", "age": 20}

Then use json.dumps to get an str object, that represents the JSON object.

json_obj = json.dumps(obj)

here, json_obj is a string, so you can write it using conventional methods. (Try that out in the interactive interpreter)

After that read this page for info on templates in the webapp framework (I use Django, and I'm not sure if webapp uses the same templating system - though it looks similar, so better read up)

If you're talking about the jQuery AJAX POST, you'll have to generate the (X)HTML/XML/whatever on the server side, UNLESS, of course, you're causing some post-POST URL to be loaded in an iframe.

If that did not answer what you wanted, clarify your question a bit. And it is very unlikely IMO that anyone would post the answer with code to jsfiddle.

Upvotes: 3

Related Questions