【发布时间】:2015-06-22 02:05:11
【问题描述】:
我一直在尝试在第一次渲染之前在模板中添加或更新变量。我有一个 Ajax 请求,它发送一个工作正常的 POST 请求,但是当我尝试将新变量 destinations 返回到同一页面/模板 index.html 时,它没有出现。
如何解决此问题?
view.py
def index(request):
if request.method == 'POST':
dayset = request.POST.get('the_point')
dest = Destination(get_cons(dayset))
destinations = dest.latlond()
context = {'destinations': destinations}
render(request, 'index.html', context)
else:
objan = Antennas(antenas)
antposition = objan.getAntennas()
context = {'antposition': antposition}
return render(request, 'index.html', context)
寺庙索引.html
<html>
<head>
<meta charset=utf-8 />
<title>DAKARmob</title>
{% load staticfiles %}
<script type="text/javascript" src="{% static "scripts/main.js" %}"></script>
<body>
<script type="text/javascript">
{% for pos in antposition %}
var marker = L.marker([{{pos.1}}, {{pos.2}}], {
icon: L.mapbox.marker.icon({
'marker-color': '#b9e841'
}),
draggable: false
}).on('click', onAnte);
antenas[{{pos.0}}] = [{{pos.1}}, {{pos.2}}];
cluster_ant.addLayer(marker);
{% endfor %}
map.addLayer(cluster_ant);
function onAnte(e) {
var latl = this.getLatLng();
var aux = [latl.lat,latl.lng];
var result = getKeysForValue(antenas, aux);
new_point(result[0]);
function new_point(id) {
console.log(id);
$.ajax({
url : "/", // the endpoint
type : "POST", // http method
data : { the_point : id }, // data sent with the post request
success : function(res) {
console.log("success"); // another sanity check
}
});
}
// OTHER FUNCTIONS FOR THE FUNCTION OF AJAX AND DJANGO
</script>
<div style="position:absolute; top:900px; left:10px; ">
{{ destinations }}
</div>
</body>
</html>
【问题讨论】:
-
你能添加你的模板代码吗?
-
如果您通过 ajax 发送,您不想重新渲染所有页面。我建议你返回一个 JSON 响应,并通过模板中的 javascript 从这个 JSON 中获取数据。除非您刷新整个页面,否则您将无法获取 {{destinations }}。
-
我宁愿不刷新页面。 @Celeo
-
在此处发布您的 AJAX 请求代码
标签: python django django-forms django-templates django-views