使用Ajax、jQuery将数据发布到Django

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (137)

我想将html5地理位置数据提交给django管理后端。不过,我不确定是否在index.html javascript中正确设置了javascript,jQuery和ajax。我能够在html页面中显示纬度和经度,但无法将数据发布到django。

index.html

{% extends 'ajax/base.html' %}
{% block body %}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Get Your Location</button>
<p id="demo"></p>
<button type="button" id="btn_submit" class="btn btn-primary form-control">Submit</button>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;  
}

$(document).ready(function(){
    $('#btn_submit').on('click', function(){
        $.ajax({
            type: "POST",
            url : "insert",
            data: {
                latitude: $position.coords.latitude,
                longitude: $position.coords.longitude,

                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function(){
                alert("Saved Data!");
            }
        });
    });
});
</script>

{% endblock %}

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'ajax/css/bootstrap.css' %}"/>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python - Django Simple Submit Form With Ajax</h3>
        <hr style="border-top:1px dotted #000;"/>
        {% block body %}
        {% endblock %}
    </div>
</body>
<script src = "{% static 'ajax/js/jquery-3.2.1.js' %}"></script>
<!--<script src = "{% static 'ajax/js/script.js' %}"></script>-->
</html>

models.py

from django.db import models

class Geolocate(models.Model):
    latitude = models.FloatField(blank=False, null=False)
    longitude = models.FloatField(blank=False, null=False)

views.py

from django.shortcuts import render, redirect
from .models import Geolocate

def index(request):
    return render(request, 'ajax/index.html')

def insert(request):
    geolocate = Geolocate(latitude=request.POST['latitude'], longitude=request.POST['longitude'])
    geolocate.save()
    return redirect('/')

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^insert$', views.insert, name="insert")
]
提问于
用户回答回答于

最可能的原因是模板中没有CSRF令牌标记。

你必须把它放在模板里,就像这样:

{% csrf_token %}

你还可以定义视图不需要CSRF令牌:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

扫码关注云+社区

领取腾讯云代金券