访问用户位置(仅城市名称)(非地图)

2024-09-30 20:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个博客应用程序,但我遇到了一个问题

我想做的事

我正在尝试访问用户位置,如:-城市或州。我不想进入地图。我只想访问用户的城市名称

我试过什么

  • 我尝试通过JavaScriptGoogle Apis访问位置,它完美地显示了位置。但我没有找到任何方法将用户在数据库中的位置从前端保存到后端。所以我放弃了这个方法。下面↓ 代码正在显示FrontEnd Code of JavaScript

     <script>
    
    let thisElement = $(this)
    $.ajax({
      url: "https://geolocation-db.com/jsonp","/update_counter/",
      jsonpCallback: "callback",
      dataType: "jsonp",
      success: function(location) {
        $('#country').html(location.country_name);
        console.log('success')
        thisElement.parent().parent().fadeOut();
      }
    });
    
    </script>
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    
    <div>Country: <span id="country"></span></div>
    
  • 然后我试着MaxMind's GeoIP它对我也不起作用。(答案也太旧了)

  • 然后我尝试了THIS,但它们并没有连接到任何模型,所以可能很难在数据库中保存用户位置

我不知道该怎么办

任何帮助都将不胜感激

先谢谢你


Tags: 方法用户httpscom数据库scriptajaxlocation
2条回答

使用Ajax

在得到你的位置后。使用Ajax将其发送到django,然后使用django保存到db

  1. 我认为你不能在第一次成功后就开始新的ajax。在本例中,在完成第一个ajax之后,您应该在页面元素上编写City
  2. 在页面上获得带有City的元素后,可以尝试为changing element启动新的ajax
$( "<your element with City name>" ).change(function() {
      const city = <something where you wrote your City>;
        $.ajax ({
        url : <your url>,
        data: {
                'city': city,
            },
        success: function (data) {
                <do something if you want>;
            }
        });
    });
  1. Django:你可以阅读this来理解ajax(我只是用谷歌搜索了一下)。简单地说,您向服务器启动ajax(为其创建url点),为该url创建将数据保存到db的函数。 (对不起我的英语)

网址:

...
path('<your url>', views.your_function, name='ajax-something'),
...

观点:

def your_function(request):
     city = request.GET.get('city')
     <here you write data to db>

     return <what you want to do>

相关问题 更多 >