从JavaScript传递变量到服务器(Django)

5

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

$(document).ready(function(){
    $.post("/location", pos)
});

在Django中,我在urls.py中创建了一个名为/location的url,通过request.POST(pos)在views.py中捕获pos变量,我使用它来执行距离查找。
我发现该变量未传递到Django服务器,请问有人能指导我出错的地方吗?

5
尝试使用 $.post("/location", {position : pos}); 替代。在服务器端通过 request.POST['position'] 访问它(我想)。 - Joe
@Joe 尝试了你的建议,但似乎不起作用。 - kurrodu
1
@Joe 是不是因为 (document).ready(function() 在用户点击允许(发送当前位置)之前就被执行了? - kurrodu
1个回答

7
我已经使用下面的代码,将Google地理位置API中的JavaScript位置变量(pos)分配给HTML表单中的一个输入元素(id="location")。
document.getElementById('location').value = pos

以下是我的HTML表单。
<form id = "geolocation" action="/location" method="POST" >
            {% csrf_token %}
        <input type="text" id = "location" name="location" value="" />
        <input type="submit" />

</form>

然后在我的谷歌地理位置API中,我通过添加以下代码行来自动提交表单。
document.getElementById("geolocation").submit(); 

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

user_location = request.POST.get('location')

这里是谷歌地理定位API的链接

我插入了一段代码摘录,以便您知道我在谷歌地理定位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(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接