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" ...
You 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With