在这种特定情况下,如何将数据从Django中的模板传递到Javascript [英] How can i pass data from template in Django to Javascript in this specific case

查看:41
本文介绍了在这种特定情况下,如何将数据从Django中的模板传递到Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google map api,并且试图将数据(经度和纬度)传递到模板,然后使用javascript中的数据显示特定位置.

I am using Google map api and i am trying to pass the data (longitude and latitude) to the template then use the data in the javascript to show a specific location.

location.html

location.html

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

同一页面的javascript

javascript of the same page

<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>

我试图按字面值替换该值,但是它不起作用.解决此问题的最佳方法是什么?

I am tried to replace the value literally but it wont work. What is the best way to solve this?

推荐答案

首先,您要将数据分配到 div 中.没有适当的value属性.这是通过使用 getAttribute()方法解决的.

First of all you are assigning your data into a div. Which doesn't have a proper value attribute. Here is a work around by using getAttribute() method.

分配一个名为'value'的属性及其对应的数据:

Assign an attribute named 'value' and it's corresponding data:

location.html

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的属性来访问数据:

In your javascript function, access the data by getting the attribute of your div ids named value:

<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>

这篇关于在这种特定情况下,如何将数据从Django中的模板传递到Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆