我使用“ google-map api”创建了django程序。从“ map.js”读取“ mapinit(json-data)”
<body onload="mapinit('{{ data }}')">
<!-- create a map area with shop information -->
<div class="wrapper">
<div id="shopinfomation"></div>
<div id="map_canvas1" style="width: 500px; height: 500px"></div>
</div>
<!-- post action from html is ok! -->
<h3>category 1</h3>
<form class="specific_form" action="{% url 'index_search' '1A' %}" method="POST">
{% csrf_token %}
<input type="submit" class="btn-flat-border" value="ramen" /> search ramen shops
</form>
外部javascript有一些动作,例如ajax,重定向。现在,我直接在写网址。
// get a shop detail
$.ajax({
type: "POST",
url: "/gmarker/search/detail/" + json.shops[i]['place_id'],
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", Cookies.get('csrftoken'));
}
}).done(function(data){
shopinfomation.innerHTML = 'ajax success. shop information...';
}).fail(function(){
shopinfomation.innerHTML = 'ajax error.';
});
我想用这个。
console.log("{% url 'index_search' '2' %}")
我想要。
/gmarker/search/2
但是chrome输出是...来的是同一个。
{% url 'index_search' '2' %}
urlpatterns = [
path('', views.index, name='index'),
path('search/<str:searchcode>', views.index, name='index_search'),
path('search/detail/<str:place_id>', views.searchdetail, name='detail_search'),
path('result/<str:searchcode>', views.index, name='index_result'),
]
外部javascript无法读取模板标记?
是的,外部javascript无法使用模板变量。您需要做的是从内部javascript这样发送数据。 在mymap.html
<script>
var TemplateVar = {
my_url: "{% url 'index_search' '2' %}"
}
</script>
<script src="{% static 'js/map.js' %}"></script>
现在,在map.js中
my_url = TemplateVar.my_url; // Taking json attribute from script of mymap.html
console.log(my_url); // You should get what you are expecting
额外:您可能需要转义变量以防止某些攻击