Error: Uncaught SyntaxError: Unexpected token &

13,976

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))
Share:
13,976
dnelson
Author by

dnelson

Junior Engineer

Updated on June 08, 2022

Comments

  • dnelson
    dnelson almost 2 years

    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" ...