Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Uncaught SyntaxError: Unexpected token &

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" ... 
like image 985
dnelson Avatar asked Jan 20 '14 09:01

dnelson


1 Answers

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))
like image 90
Igor Chubin Avatar answered Oct 04 '22 12:10

Igor Chubin