如何从客户端检索纬度和经度坐标而不需要 POST 一次?

How do I retrieve lat & long coordinates from the client without them needing to POST once?

一旦他们同意共享它们,我想对他们的 lat/long 进行一些服务器端处理——我希望该处理的结果与用户在同一页面中在他们 "Allow" 位置访问之后立即进入。

目前,我能够检索到它们的坐标,但删除了 POST。因此,当他们 "Allow" 时,我会填写一个隐藏的 lat/long 表格,并等待他们 POST 表格,然后再使用 Geodjango 进行服务器端处理。

有什么有效的方法可以在坐标可用时立即将坐标发送到服务器,或者快速检索估计位置?

是的,您可以轻松做到这一点:

  • 制作一个视图,将 POST 参数作为 JSON

Python样本:

class MyJsonForAjaxView(generic.View):

    def get(self, request, *args, **kwargs):
        return JsonResponse({'key': value}, safe=False)
  • 使用 POST 方法在 JavaScript 中调用该视图(= AJAX 调用):

JavaScript代码:

$.ajax({
    method: 'post',
    type: 'json',
    cache: false,
    url: 'my_json_url',
    data: {'lat': your_lat, 'lgn': your_lgn}
}).done(function(data) {
    alert('call successfull!!!');
    /* data is filled with Django result, here {'key': value} */
    /* todo: remember the call has been made and it's registered on Django side */
}).fail(function(data) {
    alert('fatal error!');
}).always(function() {
    /* whatever the result, always do something here */
});

您可以在获得所需内容后立即在后台执行此操作