簡體   English   中英

在這種特定情況下,如何將數據從Django中的模板傳遞到Javascript

[英]How can i pass data from template in Django to Javascript in this specific case

我正在使用Google Map api,並且嘗試將數據(經度和緯度)傳遞到模板,然后使用javascript中的數據顯示特定位置。

location.html

{% for venue in property_listing %}
      {{ venue.address }}</br>
      <div id="long">{{ venue.longitude }}</br>
      <div id="lat">{{ venue.latitude }}</br>
{% endfor %}

同一頁面的javascript

<script>
      var latitude = REPLACE HERE;
      var longitude = REPLACE HERE;
      // Initialize and add the map
      function initMap() {
      // The location of Uluru
      var uluru = {lat: latitude, lng: longitude};
      // The map, centered at Uluru
      var map = new google.maps.Map(
          document.getElementById('map'), {zoom: 15, center: uluru});
      // The marker, positioned at Uluru
      var marker = new google.maps.Marker({position: uluru, map: map});
    }


    </script>

我試圖按字面值替換該值,但是它將無法工作。 解決此問題的最佳方法是什么?

首先,您將數據分配到div中 沒有適當的value屬性。 這是通過使用getAttribute()方法解決的。

分配一個名為“值”的屬性及其對應的數據:

location.html

{% for venue in property_listing %}
      {{ venue.address }}</br>
      <div id="long" value="{{ venue.longitude }}">{{ venue.longitude }}</br>
      <div id="lat" value="{{ venue.latitude }}">{{ venue.latitude }}</br>
{% endfor %}

在您的javascript函數中,通過獲取名為value的div id的屬性來訪問數據:

<script>
      var latitude = document.getElementById('lat').getAttribute("value");
      var longitude = document.getElementById('long').getAttribute("value");
      // Initialize and add the map
      function initMap() {
      // The location of Uluru
      var uluru = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
      // The map, centered at Uluru
      var map = new google.maps.Map(
          document.getElementById('map'), {zoom: 15, center: uluru});
      // The marker, positioned at Uluru
      var marker = new google.maps.Marker({position: uluru, map: map});
    }
</script>

這應該可以解決問題:

<script>
      var latitude = {{ venue.latitude }};
      var longitude = {{ venue.longitude }};
      // Initialize and add the map
      function initMap() {
      // The location of Uluru
      var uluru = {lat: latitude, lng: longitude};
      // The map, centered at Uluru
      var map = new google.maps.Map(
          document.getElementById('map'), {zoom: 15, center: uluru});
      // The marker, positioned at Uluru
      var marker = new google.maps.Marker({position: uluru, map: map});
    }


    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM