最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Error: Uncaught SyntaxError: Unexpected token & - Stack Overflow

programmeradmin3浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 17

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))

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?

发布评论

评论列表(0)

  1. 暂无评论