(Comments)
Hi Guys,
I would like to explain some of the complex issues we might come across while sending data using Ajax.
When we send simple key, value pairs in the javascript object, we can simply generate the JSON object like this:
// Javascript Code data = { 'key1': 'value1', 'key2': 'value2' }
We can access it simply in Django view
# Django Code print request.POST['key1'] # prints value1 if value1 is not array
Let us assume a javascript JSON object as below
// Javascript Code data = { "key1": [1,2,3], "key2": "simple string" }
We need to use getlist in Django to access array items
# Python Code key1 = request.POST.getlist("key1[]") #Dont forget []. It returns the list [1,2,3] key2 = request.POST['key2'] #Simple strings can be accessed normally
Let us assume we are sending some complex data like this.
// Javascript Code data = { "key1": {"a": "b"}, //It can be as deep/complex as you want. Dictionary in a dictionary in python. JSON object in JSON object in javascript. "key2": [1,2,3], //Some list "key3": "simple string" }
Since key1 is a JSON object, we need to convert it(not the whole data) to JSON string before sending using ajax.
// Javascript Code data['key1'] = JSON.stringify(data['key1'])
We need to convert this JSON string to dictionary in Python.
# Django Code key1 = json.loads(request.POST['key1']) # request.POST['key1'] returns a string but json.loads converts it to dictionary key2 = request.POST.getlist("key2[]") #Returns a list key3 = request.POST['key3'] #Simple string can be accessed directly.
Ajax call:
I use the below javascript code when sending ajax requests
// Javascript Code $.ajax({ "url": url, "type": "post", "data": data //Data that we prepared previously, "success": success_callback, "error": error_callback })
Do you know any better way to do this ? Feel free to mention in comments.
We develop web applications to our customers using python/django/angular.
Contact us at hello@cowhite.com
Comments