1

i send data from javascript to views,py using the following javascript code

Javascript:

$(document).ready(function(){
  console.log("js2 working");
  var jsonData={},a=0,key;
  $("#submit-button").click(function(e){
  e.preventDefault();
  $('.field').each(function () {
    a+=1;
    key=String(a);
    jsonData[key] = this.value;
  });
  console.log(JSON.stringify(jsonData));
  $.get('details',{"data":JSON.stringify(jsonData)}).done(function(){

 console.log("posted successfully");
});
});
});

i get a json string:

{"1":"text","2":"text2",3:"text3"}

int the views.py using request.get i need to extract each value in views.py

here is my code in views.py:

def details(request):
  latest_question_list = Question.objects.order_by('id')
  count=0
  for question in latest_question_list:
    count+=1
    answer=request.GET['data']
    jsonData=json.loads(answer)
    answer=jsonData(str(count))
    entry = Answer(question = question,answer=answer)
    entry.save()
  return HttpResponse("feedback:contactus")

i am getting the json in views.py as shown above the problem is while trying to extract value. please help me find a solution

1
  • 1
    what is the error exactly? Commented Jul 24, 2015 at 5:06

1 Answer 1

1

jsonData is converted to a dictionary so that you can do the following:

>>> print len(jsonData)
3
>>> print text = jsonData['1']
'text'
>>> print jsonData['2']
'text2'
>>> print jsonData['3']
'text3'

As for your question:

answer = request.GET['data']
jsonData = json.loads(answer)

for count, question in enumerate(latest_question_list):
    answer = jsonData[str(count + 1)]
    entry = Answer(question=question, answer=answer)
    entry.save()

return HttpResponse("feedback:contactus")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate i have been struggling to find this small mistake for a long time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.