Reputation: 265
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
Upvotes: 1
Views: 1770
Reputation: 52103
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")
Upvotes: 1