【问题标题】:passing variable from javascript to server (django)将变量从javascript传递到服务器(django)
【发布时间】:2013-09-07 00:56:57
【问题描述】:

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

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

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

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

【问题讨论】:

  • 尝试改用$.post("/location", {position : pos});。使用request.POST['position'](我认为)在服务器端访问它。
  • @Joe 尝试了您的建议,但似乎不起作用。
  • @Joe 难道是因为(document).ready(function() 甚至在用户点击允许(发送当前位置)之前就被执行了吗?

标签: javascript jquery python django geolocation


【解决方案1】:

我已使用以下代码将 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')

这里是a link 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(); 

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多