将变量从javascript传递到服务器(django)

kur*_*odu 5 javascript python django jquery geolocation

我试图使用jQuery的post方法将用户当前位置变量(在用户点击允许后)从浏览器发送到Django服务器.当前位置存储在变量中pos.

$(document).ready(function(){
    $.post("/location", pos)
});
Run Code Online (Sandbox Code Playgroud)

在django中,我/location在urls.py中创建了一个url ,它捕获了views.py中的pos变量request.POST(pos),我用它来进行距离查找.

我看到变量没有传递给django服务器,有人可以告诉我哪里出错了吗?

kur*_*odu 7

我已使用以下代码将Google地理位置API中的JavaScript位置变量(pos)分配为HTML格式的输入元素(id ="location")

document.getElementById('location').value = pos
Run Code Online (Sandbox Code Playgroud)

下面是我的HTML表单

<form id = "geolocation" action="/location" method="POST" >
            {% csrf_token %}
        <input type="text" id = "location" name="location" value="" />
        <input type="submit" />

</form>
Run Code Online (Sandbox Code Playgroud)

然后在我的谷歌地理定位API中,我通过添加以下代码行自动提交表单

document.getElementById("geolocation").submit(); 
Run Code Online (Sandbox Code Playgroud)

最后在Django Views.py文件中,我使用'POST'方法从我在使用变量的函数中从客户端获取位置

user_location = request.POST.get('location')
Run Code Online (Sandbox Code Playgroud)

以下是Google Geolocation API 的链接.

我已经从我的代码中插入了摘录,以便您可以知道我在Google Geolocation API中使用了上述JavaScript代码的确切位置.

var infowindow = new google.maps.InfoWindow({
    map: map,
    position: pos,
    content: 'Location found using HTML5.'
  });
  // the below line has been inserted to assign a JS variable to HTML input field called 'geolocation' 
document.getElementById('location').value = pos
map.setCenter(pos);
// the below line has been inserted to autosubmit the form.  
document.getElementById("geolocation").submit(); 
Run Code Online (Sandbox Code Playgroud)