如何在Django中将数据传递给javascript

2024-09-30 10:38:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种从django视图向index.js脚本传递数据的方法。 简单视图示例:

   def map_display(request):
        data = [
        {'lat': 52.20415533, 'lng': 21.01427746},
        {'lat': 52.20418, 'lng': 21.014386},
        ]
        data = json.dumps(data)
        return render(request, 'index.html', {"data": data} )

如何将数据列表到flightPlanCoordinates变量

index.js

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 3,
    center: { lat: 0, lng: -180 },
    mapTypeId: "terrain",
  });
  const flightPlanCoordinates = {{ data}};  # <--- pass here
  const flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    geodesic: true,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2,
  });
  flightPath.setMap(map);
}

index.html

<html>
  <head>
    <title>Simple Polylines</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <link href= "{% static 'css/style.css' %}"  rel="stylesheet" type="text/css">
    <script src="{% static 'js/index.js' %}" ></script>
  </head>
  <body>
    <div id="map"></div>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=........=initMap&libraries=&v=weekly"
      async
    ></script>
  </body>
</html>

Tags: src视图mapdataindexrequesthtmljs
1条回答
网友
1楼 · 发布于 2024-09-30 10:38:25

在加载index.js之前,我会直接在index.html中设置它

<script> const flightPlanCoordinates = {{ data }}; </script>
<script src="{% static 'js/index.js' %}" ></script>

或者,如果函数直接在HTML中执行,我会将其作为参数发送

<script src="{% static 'js/index.js' %}" ></script>
<script> initMap({{ data }}) </script>

编辑:

另请阅读@AbdulAzizBarkat关于XSS vurnerability的评论并参见article

相关问题 更多 >

    热门问题