发送Django变量到javascript

时间:2018-12-21 01:52:13

标签: javascript django

我正在尝试在javascript脚本中访问Django占位符,该占位符是数据库中的数组,供在three.js中使用

在views.py中,我有coord_xcoord_ycoord_z变量,它们是通过以下方式来自数据库的:

cur.execute("""SELECT x FROM pc_processing.basesample""")
coord_x = cur.fetchall()
cur.execute("""SELECT y FROM pc_processing.basesample""")
coord_y = cur.fetchall()
cur.execute("""SELECT z FROM pc_processing.basesample """)
coord_z = cur.fetchall()

在我的模板html中(注释掉了随机测试数字,非常适合测试):

...
for (var i = 0 ; i < numpoints ; i++) {

    var x = {{coord_x}};
    var y = {{coord_x}};
    var z = {{coord_x}};

    // var x = Math.random() * (0 - 1) + 1
    // var z = Math.random() * (0 - 1) + 1
    // var y = Math.random() * (0 - 1) + 1

    var dotGeometry = new THREE.Geometry();
    dots.push(dotGeometry);
    dotGeometry.vertices.push(new THREE.Vector3(x, y, z));
    var dotMaterial = new THREE.PointsMaterial( { size: 3, sizeAttenuation: false, color: 0xFF0000 });
    var dot = new THREE.Points( dotGeometry, dotMaterial);
    scene.add(dot);
}
...

我猜我需要以某种方式遍历x,y,z变量吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试这样:

通过views.py中的上下文发送变量:

context = { 'coord_x': 20, 'coord_y': 10, 'coord_z': 30}
return render(request, 'template.html', context)

然后在模板中将变量附加到window对象:

<script>
window.x = "{{coord_x}}"
window.y = "{{coord_x}}"
window.z = "{{coord_x}}"
</script>

并在您的JS文件中使用它。如果变量是列表,则必须遍历它们:

var currX = x[i];
var currY = y[i];
var currZ = z[i];

dotGeometry.vertices.push(new THREE.Vector3(currX, currY, currZ));

一种更好的方法是将这些变量不是作为列表发送,而是作为字典发送。在views.py中是这样的:

context = { 'coordinates': [{'x':1, 'y':2, 'z':3}, {'x':1, 'y':2, 'z':4}] }
return render(request, 'template.html', context)

将它们附加在JS中:

<script>
window.coordinates = "{{ coordinates }}";
</script>

并像这样使用它:

coordinates.forEach(function(i){
...
dotGeometry.vertices.push(new THREE.Vector3(i.x, i.y, i.z));
...
}