无法在django项目中的javascript函数和ajax之间传递变量
这似乎是一个恰当的noob问题,所以很抱歉,但我似乎无法解决它,所以我正在寻求帮助 我在.js文件中有一个函数,它与GooglePlaces库交互,自动完成表单中的字段。然后,我有一个ajax函数,当您单击submit按钮时运行,该按钮在django会话中创建变量。我感兴趣的数据是无法在django项目中的javascript函数和ajax之间传递变量,javascript,jquery,django,ajax,Javascript,Jquery,Django,Ajax,这似乎是一个恰当的noob问题,所以很抱歉,但我似乎无法解决它,所以我正在寻求帮助 我在.js文件中有一个函数,它与GooglePlaces库交互,自动完成表单中的字段。然后,我有一个ajax函数,当您单击submit按钮时运行,该按钮在django会话中创建变量。我感兴趣的数据是lat和long 然而,由于某些原因,我似乎无法将数据从一个传递到另一个。我知道ajax函数正在工作,因为如果我输入固定值,它们会传播到django,但我似乎无法让它动态更新 const csrf = document
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调用移到了autocomplete函数中,但它只在我单击submit按钮时起作用,在我按下enter键时不起作用,因此我需要重新学习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)
}
})
})
})
}
您在哪里调用
自动完成位置()
?尝试将该函数中的lat和long作为参数传递,例如自动完成位置(lat,long)
谢谢您的建议。我添加了这个,但没有什么不同。至于在调用它时,它被加载到html的头部。