我有一个从服务器返回的JSON对象。它看起来像这样:
{"1":{"id":"1","name":"autos"},
"2":{"id":"2","name":"business"},
"3":{"id":"3","name":"cities"},
"4":{"id":"4","name":"drama"},
"5":{"id":"5","name":"movies"},
"6":{"id":"6","name":"finance"},
"7":{"id":"7","name":"electronics"}}
所以我将模板渲染为包含JSON的字符串:
<h3>Ugly, raw list. Yuck !</h3>
1: {{ interests }}
<ul>
{% for k,v in interests.items %}
<li>{{k}}. - {{ v }}</li>
{% endfor %}
</ul>
template_name = 'socialauth/interests.html'
html = render_to_string(template_name, RequestContext(request, {'interests': ResultDict,}))
因此我得到了:
<h3>Ugly, raw list. Yuck !</h3>
1: {"1":{"id":"1","name":"autos"},"2":{"id":"2","name":"business"},"3":{"id":"3","name":"cities"},"4":{"id":"4","name":"drama"},"5":{"id":"5","name":"movies"},"6":{"id":"6","name":"finance"},"7":{"id":"7","name":"electronics"}}
<ul>
</ul>
所以看起来我的{{interests}}变量不被视为字典。但为什么 ?更重要的是,现在我将渲染列表包含到父模板中,该模板也呈现为字符串(因为我用ajax加载它)。最终结果如下:
模板:
<div class="connect-twitter" style="background:#f8f8f8">
<div id="likes-list">
{{ likes|safe }}
</div>
<a href="#" class="submit-step-2">Proceed</a>
</div>
结果:
Content-Type: text/html; charset=utf-8
{"html": "<h3>Ugly, raw list. Yuck !</h3>\n\n1: {"1":{"id":"1","name":"autos"},"2":{"id":"2","name":"business"},"3":{"id":"3","name":"cities"},"4":{"id":"4","name":"drama"},"5":{"id":"5","name":"movies"},"6":{"id":"6","name":"finance"},"7":{"id":"7","name":"electronics"}}\n\n<ul>\n \n</ul>"}
当这段代码插入到html中时,它看起来很糟糕:
http://img204.imageshack.us/img204/3858/listaxv.png
到底是什么?为什么它不能正常呈现为字符串,而是添加了一些“内容类型”标题?
答案 0 :(得分:0)
看起来模板变量interests
只是一个带有json响应的字符串。字符串在模板中被转义,这就是为什么你最终得到所有“。”检查服务器的响应是否被正确解析。
要验证类型,您可以使用类型类,即type(ResultDict)
。
答案 1 :(得分:0)
你是否对响应做了任何转换,比如$ parseJSON(string)或eval(string)将响应转换为JS对象?