我在python中有一个列表列表:
[["blue1", "blue2", "blue3", "blue4"], ["blue5", "blue6", "blue7", "blue8"], ["blue9", "blue10", "blue11", "blue12"], ["blue13", "blue14", "red", "blue15"]]
当我在这个列表上调用json.dump然后在javascript中使用JSON.parse时,我没有在javascript中获得等效列表。有什么建议吗?
在python中我有dumps语句:
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]);
控制台返回[,然后是三个未定义的
答案 0 :(得分:0)
您只获取属性(这是一个字符串),您永远不会将其解析为数组。所以board [0]只是字符串的第一个字符。使用JSON.parse,
var board = JSON.parse(document.currentScript.getAttribute('test'));
但是,还有另一个问题:您使用|safe
模板过滤器来关闭自动转义功能。但是JSON 不安全,例如它包含"
个字符。如果您的HTML读取test="[["blue1"],
等,则测试属性的值为"[["
。所以你需要删除那个过滤器,以便Django可以为你逃避这些引用。