2014-01-20 57 views
3

从模型向JSON数据发送JSON数据时出现错误。它看起来像编码导致了错误,但我找到的所有例子都适用于其他人。我该如何正确地将模型数据从我的视图发送到JavaScript?错误:未捕获SyntaxError:意外的令牌&

视图代码:

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代码:

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

错误Uncaught SyntaxError: Unexpected token &

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

除了下面的答案:看看Django大括号。在那里,json视图已经实现了 http://django-braces.readthedocs.org/en/latest/other.html#jsonrequestresponsemixin – ProfHase85

+0

@ ProfHase85感谢您的链接。我会看看。 – dnelson

回答

13

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

该字符串被自动转义render_to_response

要避免这种情况,您必须标记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)) 
+0

谢谢!我有类似的问题,这也帮助我解决了我的问题! – naiveDeveloper

+0

谢谢你..帮我也:) –

0

您的数据是html编码的。它应该来自服务器的引号和所有。是render_to_response做某种编码? json_data在该功能之前看起来像什么?

相关问题