【发布时间】:2020-11-13 22:52:26
【问题描述】:
这似乎是一个适当的菜鸟问题,所以很抱歉,但我似乎无法解决它,所以我正在寻求一些帮助。
我的 .js 文件中有一个函数,它与 Google Places 库交互以自动完成表单中的字段。然后我有一个 ajax 函数,当您单击在 django 会话中创建变量的提交按钮时运行该函数。我感兴趣的数据是lat和long。
但是,由于某种原因,我似乎无法让数据从一个传递到另一个。我知道 ajax 函数正在工作,因为如果我输入固定值,它们会传播到 django,但我似乎无法让它动态更新。
const csrf = document.getElementsByName('csrfmiddlewaretoken');
var lat;
var lng;
function autocomplete_location() {
let defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(49.6331, -11.7247),
new google.maps.LatLng(59.4850, 1.5906));
let input = document.getElementById('id_your_location');
let options = {
bounds: defaultBounds,
types: ["address"],
fields: ["name", "geometry"],
};
let autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', function() {
// Get place info
let place = autocomplete.getPlace();
// Do whatever with the value!
lat = place.geometry.location.lat()
lng = place.geometry.location.lng()
console.log(lat)
console.log(lng)
})
}
$(document).ready(function (){
$(".btn").click(function (){
$.ajax({
url: '',
type: 'POST',
data: {
'csrfmiddlewaretoken': csrf[0].value,
'lat': lat,
'long': lng,
},
success: function (response) {
console.log(response)
window.location.replace('/new_path/')
},
error: function (error) {
console.log(error)
}
})
})
})
更新 ---------------------------------------------- -------------
我已经设法让这个工作。我已经将ajax调用移到了自动完成功能中,但是它只在我点击提交按钮时有效,当我按下回车键时它不起作用,所以我需要刷上我的JS和ajax来解决这个问题。
const csrf = document.getElementsByName('csrfmiddlewaretoken');
function autocomplete_location() {
let defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(49.6331, -11.7247),
new google.maps.LatLng(59.4850, 1.5906));
let input = document.getElementById('id_your_location');
let options = {
bounds: defaultBounds,
types: ["address"],
fields: ["name", "geometry"],
};
let autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', function() {
// Get place info
let place = autocomplete.getPlace();
// Do whatever with the value!
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
console.log(lat)
console.log(lng)
$("form").submit(function (){
$.ajax({
url: '',
type: 'POST',
data: {
'csrfmiddlewaretoken': csrf[0].value,
'lat': lat,
'long': lng,
},
success: function (response) {
console.log(response)
// this is not good. But I couldn't find a better way to redirect
// window.location.replace('/coach/')
},
error: function (error) {
console.log(error)
}
})
})
})
}
【问题讨论】:
标签: javascript jquery django ajax