【发布时间】:2020-08-16 20:04:33
【问题描述】:
这里是新手。我正在为介绍 CS 课程使用公寓大楼和公寓单元的数据库,并尝试使用烧瓶构建 Web 应用程序。
在 application.py 中,我有这样的东西:
locationdict =
{
"Complex A": [1, 2, 3],
"Complex B": [4, 5, 6]
}
JSONlocationdict = json.dumps(locationdict, sort_keys=True)
return render_template("start.html", JSONlocationdict=JSONlocationdict)
但是,当我尝试从 JavaScript 中的字典访问该数据时,似乎没有任何效果。 HTML 页面大致如下所示:
<button onclick = "getUnits(this)" id="Complex A"> Complex A </button>
<script>
function getUnits(arg) {
var locationName = arg.getAttribute("id");
var JSONlocationdict = "{{ JSONlocationdict }}";
console.log(JSONlocationdict)
// In the console, this is what you see:
// {"Complex A": [1,2,3], "Complex B", [4,5,6]}
var obj = JSON.parse(JSONlocationdict);
console.log(obj); // this returns the error
// Then you see this in the console:
// Uncaught SyntaxError: Unexpected token & in JSON at position 1
// at JSON.parse (<anonymous>)
// at getUnits (start:88)
// at HTMLButtonElement.onclick (start:119)
var units = obj["Complex A"];
console.log(units);
// That last request to log to the console does nothing so far.
}
</script>
我尝试使用不同的方法将原始字典转换为 JSON,例如 jsonify 和 json.loads() 而不是 dumps()。我已经在 stackoverflow 上浏览了大量关于 SyntaxError: Unexpected token 的条目,但我似乎无法得到任何工作。有什么想法吗??
似乎唯一可靠的是有两个单独的页面 - 用户可以从公寓大楼列表中选择的第一页,然后将它们发送到第二页,然后他们可以选择单元。
如果他们可以单击公寓大楼的按钮,然后在同一页面上动态生成该公寓大楼的可用单元列表,那就太好了。
【问题讨论】:
-
首先将您的线路更改为
var JSONlocationdict = "{{ JSONlocationdict|safe }}";。 (这假设您使用 Jinja2 作为您的模板引擎)。这将防止 html 实体被转义序列替换。 -
我应该这样做
var JSONlocationdict = '{{ JSONlocationdict|safe }}';这样 json 字符串就不会引起头痛。 -
这成功了!谢谢!!
标签: javascript python json flask