将客户端数据发送到服务器端的问题(Django)

时间:2019-05-19 12:19:21

标签: javascript python jquery ajax django

我正在尝试将客户端数据(纬度和经度的html5 api)发送到服务器端。我不熟悉JS,但是找到了两个用于纬度和经度的JS函数的代码:

function latitude() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            return document.getElementById('latitude').setAttribute("value", position.coords.latitude);
        }
        );
    }
    else {
        alert("Sorry, your browser does not support HTML5 geolocation.");
    }
}
function longitude() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            return document.getElementById('longitude').setAttribute("value", position.coords.longitude);
        }
        );
    }
    else {
        alert("Sorry, your browser does not support HTML5 geolocation.");
    }
}

然后我创建了将接收数据的django表单:


class CordsForm(forms.Form):
    latitude = forms.CharField(widget=forms.TextInput(
        attrs={'id': 'latitude', 'type': 'hidden'}))
    longitude = forms.CharField(widget=forms.TextInput(
        attrs={'id': 'longitude', 'type': 'hidden'}))

我还创建了使用以下形式的视图:

def index(request):
    if request.method == 'POST':
        cords_form = CordsForm(request.POST)
        if cords_form.is_valid():
            latitude = cords_form.cleaned_data['latitude']
            longitude = cords_form.cleaned_data['longitude']
            print(longitude) # only for testing
            print(latitude) # only for testing
    else:
        cords_form = CordsForm()
    return render(request, 'weather/index.html', {'form': cords_form})

这是索引页:

{% extends 'weather/base.html' %}
{% block content %}
<form method="POST" id="geoform" name="geoform">
    {% csrf_token %}
    {{ form.latitude }}
    <script>latitude();</script>
    {{ form.longitude }}
    <script>longitude();</script>
</form>
<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        document.getElementById("geoform").submit();
    });
</script>
{% endblock content %}

每次用户访问索引页时,纬度和经度都是通过表格自动发送的,但是此代码如下:

<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        document.getElementById("geoform").submit();
    });
</script>

发送数据,但刷新页面,就像我向F5按钮发送垃圾邮件一样。索引页被访问后,我如何仅发送一次数据?

1 个答案:

答案 0 :(得分:0)

您应该本地存储:

,当您要将数据发送到服务器时,请检查并确认是否具有该功能可以发送

您应在if语句中使用此代码,以检查您的本地存储,然后运行此代码:

document.addEventListener("DOMContentLoaded", function (event) {
        document.getElementById("geoform").submit();

像这样:

var check = localStorage.getItem('posted');
if(check !== 'true'){
document.addEventListener("DOMContentLoaded", function (event) {
        document.getElementById("geoform").submit();
localStorage.setItem('posted','true')
}

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage