Django:使用 Javascript 在我的模板中解析 JSON [英] Django: Parse JSON in my template using Javascript
问题描述
我认为:
string_location = myaddress2地理数据 = []对于 g.geocode(string_location,exactly_one=False) 中的位置 (lat, lng):geodata.append((place, (lat, lng)))geodata_results = len(地理数据)数据 = {地理数据":地理数据,地理数据结果":地理数据结果}return render_to_response("business/business_view.html",数据,context_instance=RequestContext(request))
我将如何处理"/将 geodata 转换为 JSON 并将其传递给我的模板,以便我可以像数组一样循环"它?
我认为我可以这样做是否正确?如果没有,请提出更好的解决方案.
谢谢!
更新
var geodata = "[["ML奎松街<br/>菲律宾曼达维市", [10.351381999999999, 123.923535]], ["Talamban<br/>菲律宾宿务市", [10.353527, 123.91352500000001]]]";
我认为 JSON 没有被转义?如何转义 json 字符串中的特殊字符?我不断收到换行错误.
对于 PHP,我会使用 json_encode() 来解决这个问题.就像在这篇文章中一样:将 PHP 字符串传递给一个 JavaScript 变量(并转义换行符) 但是我如何在 Python/Django 中做到这一点?
你可以使用内置的 json
模块:
然后您可以简单地将结果字符串嵌入到 javascript 脚本中:
I have this in my view:
string_location = myaddress2
geodata = []
for place, (lat, lng) in g.geocode(string_location,exactly_one=False):
geodata.append((place, (lat, lng)))
geodata_results = len(geodata)
data = {"geodata": geodata, "geodata_results":geodata_results }
return render_to_response("business/business_view.html",
data, context_instance=RequestContext(request))
How would I "handle" / convert geodata into JSON and pass it to my template so that I can "loop" through it like an array?
Am I right to think that I can do it this way? If not, then please suggest on a better solution.
Thanks!
UPDATE
var geodata = "[["M. L. Quezon Street<br/>Mandaue City, Philippines", [10.351381999999999, 123.923535]], ["Talamban<br/>Cebu City, Philippines", [10.353527, 123.91352500000001]]]";
I think the JSON is not escaped? How do I escape special characters inside the json string? I keep getting a newline error.
For PHP, I would json_encode() to fix this. Like in this post: Pass a PHP string to a JavaScript variable (and escape newlines) BUT how do I do that in Python/Django?
You could use the built-in json
module:
>>> import json
>>> geodata = [ ( "Here", (1003,3004) ), ("There", (1.2,1.3)) ]
>>> json.dumps(geodata)
'[["Here", [1003, 3004]], ["There", [1.2, 1.3]]]'
You can then simply embed the resulting string inside a javascript script:
<script type='text/javascript'>
var geodata = {{ geodata|safe }};
</script>
这篇关于Django:使用 Javascript 在我的模板中解析 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!