我正在构建一个犯罪警报网站,我希望在用户提交新警报后提取用户的经度和纬度。相反,它提交了两次 lat 和 lng 有价值,另一个没有价值。
我想让它返回这个:
lucas posted a crime alert!
Alert!!! cv !!!
Crime reported from Ogbia, Bayelsa
Crime coordinates: Longitude 3.325952 | Latitude 6.599475
Category: c
March 9, 2023, 1:53 p.m.
而是像这样提交两次:
lucas posted a crime alert!
Alert!!! cv !!!
Crime reported from Ogbia, Bayelsa
Crime coordinates: Longitude 3.325952 | Latitude 6.599475
Category: c
March 9, 2023, 1:53 p.m.
lucas posted a crime alert!
Alert!!! cv !!!
Crime reported from Ogbia, Bayelsa
Crime coordinates: Longitude None | Latitude None
Category: c
March 9, 2023, 1:53 p.m.
我的观点:
def new_alert(request):
if request.method == "POST":
content = request.POST.get("content")
state = request.POST.get("state")
lga = request.POST.get("lga")
category = request.POST.get("category")
current_user = request.user
lat = request.POST.get("lat")
lng = request.POST.get("lng")
# Create a new alert
new_alert = Alert(content=content, state=state, lga=lga, user=current_user, category=category, latitude=lat, longitude=lng)
new_alert.save()
return HttpResponseRedirect(reverse("all_alerts"))
else:
return render(request, "new_alert.html")
我的Javascript:
<script>
function getLocation() {`your text`
if (navigator.geolocation) {
// Display confirmation prompt
if (confirm("Allow this website to access your location?")) {
navigator.geolocation.getCurrentPosition(sendLocation);
} else {
alert("Location access denied.");
}
} else {
alert("Geolocation is not supported by this browser.");
}
}
function sendLocation(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("Sending data: ", { lat: lat, lng: lng });
// Get the CSRF token from the form
var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// Get the form data using FormData
var form_data = new FormData(document.querySelector('#form-id'));
// Add the lat and lng values to the form data
form_data.append('lat', lat);
form_data.append('lng', lng);
// Send the AJAX request with the form data
$.ajax({
url: 'new_alert',
type: 'POST',
data: form_data,
contentType: false,
processData: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRFToken', csrftoken);
},
error: function (xhr, status, error) {
alert('Fill the fields before submitting Alert');
}
});
}
</script>
我的 HTML(我删除了下拉列表中的项目,所以这里不会太长):
<form id="form-id" action="{% url 'new_alert' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<textarea id="create-post-text" name="content" placeholder="Report crime" required></textarea>
</div>
<div class="form-group">
<label class="control-label">Where Are You Reporting From?</label>
</div>
<div class="form-group">
<label class="control-label">LGA of Origin</label>
<select name="lga" id="lga" class="form-control select-lga" required>
</select>
</div>
<div class="form-group">
<input class="form-control" name="category" placeholder="Specify a category. For example, murder, theft, vandalism, etc" required>
</div>
<button onclick="getLocation()" class="btn btn-success" id="sendLocation">Alert!</button>
</form>
问题似乎与警报提交的重复有关,其中第一次提交包含纬度和经度值,但第二次提交没有。这可能是由函数 submitAlert() 引起的,该函数发送表单数据但不包含位置信息。要解决此问题,您可以修改 submitAlert():
函数 submitAlert() {
// Get the CSRF token from the form
var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// Get the form data using FormData
var form_data = new FormData(document.querySelector('#form-id'));
// Get the latitude and longitude values from the current position
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Add the lat and lng values to the form data
form_data.append('lat', lat);
form_data.append('lng', lng);
// Send the AJAX request with the form data
$.ajax({
url: 'new_alert',
type: 'POST',
data: form_data,
contentType: false,
processData: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRFToken', csrftoken);
},
error: function (xhr, status, error) {
alert('Fill the fields before submitting Alert');
}
});
}, function(error) {
alert('Failed to get location information');
});
}