我在python中有一个列表:
[["blue1", "blue2", "blue3", "blue4"], ["blue5", "blue6", "blue7", "blue8"], ["blue9", "blue10", "blue11", "blue12"], ["blue13", "blue14", "red", "blue15"]]当我在这个列表上调用json.dump,然后在javascript中调用JSON.parse时,我不会在javascript中得到等价的列表。有什么建议吗?
在python中,我有dump语句:
test = [["blue1", "blue2", "blue3", "blue4"],["blue5", "blue6", "blue7", "blue8"],["blue9", "blue10", "blue11", "blue12"],["blue13", "blue14", "red", "blue15"]]
return render_template("game.html", test = test);在html中,我有:
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
}
</style>
<body>
<div id ="container">
</div>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="{{ url_for('static', filename='script.js') }}" test = "{{test|tojson|safe}}"></script>
</body>
</html>在script.js中,我有:
var board = document.currentScript.getAttribute('test');
console.log(board[0][0]);
console.log(board[0][1]);
console.log(board[0][2]);
console.log(board[0][3]);控制台返回一个[,然后是三个未定义的
发布于 2016-12-08 13:33:46
您只获得该属性(这是一个字符串),就不会将其解析为数组。所以板只是字符串的第一个字符。使用JSON.parse,
var board = JSON.parse(document.currentScript.getAttribute('test'));但是,还有另一个问题:使用|safe模板筛选器关闭自动转义。但是JSON是不安全的,例如它包含"字符。如果HTML读取test="[["blue1"],等,则测试属性值为"[["。所以您也需要删除那个过滤器,这样Django就可以为您转义那些引号了。
https://stackoverflow.com/questions/41028588
复制相似问题