I get an error when sending JSON data to JavaScript from the models. It looks like encoding is causing the error, but all the examples I have found work for other people. How can I properly send model data from my view to JavaScript?
view code:
def home(request):
import json
info_obj = Info.objects.all()
json_data = serializers.serialize("json", info_obj)
return render_to_response("pique/home.html", {'json_data':json_data}, context_instance=RequestContext(request))
JavaScript code:
var data = jQuery.parseJSON('{{json_data}}');
console.log(data);
The error Uncaught SyntaxError: Unexpected token &
:
var data = jQuery.parseJSON('[{"pk": 1, "model": "pique.eat" ...
I get an error when sending JSON data to JavaScript from the models. It looks like encoding is causing the error, but all the examples I have found work for other people. How can I properly send model data from my view to JavaScript?
view code:
def home(request):
import json
info_obj = Info.objects.all()
json_data = serializers.serialize("json", info_obj)
return render_to_response("pique/home.html", {'json_data':json_data}, context_instance=RequestContext(request))
JavaScript code:
var data = jQuery.parseJSON('{{json_data}}');
console.log(data);
The error Uncaught SyntaxError: Unexpected token &
:
var data = jQuery.parseJSON('[{"pk": 1, "model": "pique.eat" ...
Share
Improve this question
edited May 28, 2014 at 0:11
dnelson
asked Jan 20, 2014 at 9:35
dnelsondnelson
4671 gold badge4 silver badges16 bronze badges
1
- Additionally to the answers below: Have a look at Django Braces. There, the json view is already implemented django-braces.readthedocs.org/en/latest/… – ProfHase85 Commented Jan 20, 2014 at 9:44
2 Answers
Reset to default 17You must use "
instead of "
in the string.
The string was automatically escaped by render_to_response
.
To avoid this you must mark json_data
safe. Use mark_safe
for it.
from django.utils.safestring import mark_safe
return render_to_response(
"pique/home.html",
{
'json_data':mark_safe(json_data)
},
context_instance=RequestContext(request))
Your data is html encoded. It should come from the server with quotes and all. Is render_to_response
doing some sort of encoding? What does json_data
look like before that function?