Django - TypeError on deserializing json from jQuery POST -


i'm pushing fair amount of data via jquery ajax django app in form of json. data received server, can't parse it.

in views file, have

from django.http import httpresponse django.utils import simplejson  def savestrategy(request):   if not request.user.is_authenticated:     return httpresponse(simplejson.dumps({"response" : "failure"}))   else:      #this section here throws typeerror - expected string or buffer     #update_tasks = simplejson.loads(request.post.get("tasks", false))     #update_strategy = simplejson.loads(request.post.get("strategy", false))      update_strategy = request.post.get("strategy", false)     update_tasks = request.post.get("tasks", false)      print update_strategy      return httpresponse(simplejson.dumps({"response" : "success"})) 

which destination of

if (typeof currenttaskid !== "undefined") {     $("#save_strategy_task").trigger("click");     localtasks = json.stringify(tasks) } else     localtasks = {};  .ajax({     url : "savestrategy/",     type : "post",     data : {"strategy" : json.stringify(strategy), "tasks" : localtasks},     datatype : "json",     success : function(data) {         if (data.response == "success")             strategydetailclosehandler();     } }); 

now, when update_strategy not involved simplejson, get

{  "title":"title",  "status":"pending",  "strategy":"strategy",  "duedate":"",  "owner":"",  "metrics":"test",  "id":"3",  "outcome":"outcome1" } 

however, if try

print update_strategy["id"] 

i typeerror: string indices must integers error.

how can parse incoming json update existing model object?

there number of issues in code relating expected types of variables. example, in javascript snippet, localtasks may either javascript object {}, or may string json.stringify(tasks).

when posted server, there call

update_tasks = simplejson.loads(request.post.get("tasks", false)) 

which has potential return boolean value false if tasks isn't present in response.

what believe happening this:

  1. on client, localtasks = {}.
  2. when .ajax call occurs, doesn't know how handle tasks entry because .ajax expects key/value pairs , doesn't send contents of tasks server.
  3. the update_tasks = simplejson.loads(request.post.get("tasks", false)) code on server attempts tasks tasks isn't in request.post false returned.
  4. the json parser attempts loads(false), resulting in error.

to fix these issues:

  1. always have localtasks converted consistent type on client. ie ensure has been converted string.
  2. don't request.post.get('foo', false). instead, request.post.get('foo', '') , handle error case when empty string returned.

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -