javascript 错误:未捕获的语法错误:意外的令牌 &

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21230459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:26:22  来源:igfitidea点击:

Error: Uncaught SyntaxError: Unexpected token &

javascriptpythondjangojsonserialization

提问by dnelson

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?

从模型向 JavaScript 发送 JSON 数据时出现错误。看起来编码是导致错误的原因,但我找到的所有示例都适用于其他人。如何将模型数据从我的视图正确发送到 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:

JavaScript 代码:

var data = jQuery.parseJSON('{{json_data}}');
console.log(data);

The error Uncaught SyntaxError: Unexpected token &:

错误Uncaught SyntaxError: Unexpected token &

var data = jQuery.parseJSON('[{"pk": 1, "model": "pique.eat" ... 

回答by Igor Chubin

You must use "instead of "in the string.

您必须在字符串中使用"而不是"

The string was automatically escaped by render_to_response.

该字符串由 自动转义render_to_response

To avoid this you must mark json_datasafe. Use mark_safefor it.

为避免这种情况,您必须标记为json_data安全。mark_safe为之使用。

from django.utils.safestring import mark_safe
return render_to_response(
  "pique/home.html",
  {
     'json_data':mark_safe(json_data)
  },
  context_instance=RequestContext(request))

回答by Kavi Siegel

Your data is html encoded. It should come from the server with quotes and all. Is render_to_responsedoing some sort of encoding? What does json_datalook like before that function?

您的数据是 html 编码的。它应该来自带有引号和所有内容的服务器。正在render_to_response做某种编码吗?json_data在那个函数之前是什么样子的?