django+javascript - 如何处理来自不同来源/函数的数据?
我有一个 JavaScript 地图,当模板页面首次加载时,它从 django 视图/函数获取一些坐标,如下所示
<script type="text/javascript">
...
map.setCenter(new f.LatLng{{lat_long}}, 11);
...
</script>
:应该更新 {{lat_long}} 标签所在的同一位置。
因此,在某种程度上,我应该使页面首次加载时来自函数的 {{lat_long}} 消失,并将其替换为来自处理 ajax 请求的函数的新 {{lat_long}} 。
解决这个问题的最佳方法是什么,以便两个函数都可以在上面的 JavaScript 代码中更新相同的纬度/经度?真实的例子将受到真正的赞赏。
I have a JavaScript map that takes some coordinates from a django view/function when the template page first loads up like this:
<script type="text/javascript">
...
map.setCenter(new f.LatLng{{lat_long}}, 11);
...
</script>
I also have another function on the same views.py file handling an ajax request that does some calculations and returns new coordinates that supposed to update the same spot where {{lat_long}} tag is.
So in a way I should make the {{lat_long}} coming from the function when the page first loads up disappear and replace it with a new {{lat_long}} that's coming form the function handling the ajax request.
What would be the best way to go about this so both functions can update the same lat/long in the javascript code above? Real examples will be truly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
克里斯说的是正确的。您想要动态更新服务器的值。将代码放在现在的位置只是在页面加载时执行,您需要使用 AJAX 请求不断向服务器询问最新值。
您需要做的是创建另一个仅返回纬度和经度的 Django 视图,JSON 是最简单的方法(即采用 {"latitude": 12.2, "longitude": 11.1} 的形式)。
您的视图将执行以下操作:
在客户端,以下是使用 jQuery Javascript 库执行 AJAX 请求的示例:
What Chris said is correct. You want to dynamically update the value from the server. Putting the code where you have it now just does it when the page is loaded, you need to use an AJAX request to keep asking the server for the latest value.
What you need to do is make another Django View that just returns the latitude and longitude, JSON being the easiest way (i.e. in the form {"latitude": 12.2, "longitude": 11.1}).
Your view will do the following:
On your client side, here is an example using the jQuery Javascript library to do an AJAX request:
您在这里处理不同的时间点。
关键是,在 AJAX 请求返回新值之前,页面脚本早已设置了该值。他们在这里并没有真正的竞争。如果您想根据
lat_long
的新值更改地图中心,只需在 AJAX 成功方法中使用新值调用map.setCenter
即可。You're dealing with different points in time here.
lat_long
and feeds it in.lat_long
from server and returns it to client.The point is that the value has long been set by the on page script before the AJAX request returns a new one. They're not really in competition here. If you want to change the map center based on the new value for
lat_long
, then just recallmap.setCenter
with the new value in your AJAX success method.