我正在尝试更新用户配置文件。用户插入地址并提交后,将其转换为纬度和经度。我创建了一个条件语句:如果地理编码器状态为正常,则更改地理位置OK = 1,否则为0。当它为 1 时,运行更新函数,但纬度和经度不会传递给 formData。在第二次更新时,单击它。任何建议如何在表单数据中包含纬度和经度?
点击更新
$(document).on("click", "#updateProfile", function (e) {
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log(latitude);
console.log(longitude);
userLatitude = document.getElementById('cityLat').value = latitude;
userLongitude = document.getElementById('cityLng').value = longitude;
geoLocationOK = 1;
console.log(geoLocationOK);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
geocodeAddress(geocoder);
if(geoLocationOK == 1){
updateProfile();
}else{
console.log("not ok");
e.preventDefault();
}
});
这是更新功能
function updateProfile(){
console.log(geoLocationOK);
$('#rootwizard').formValidation({
framework: 'bootstrap',
excluded: [':disabled'],
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
live: 'enabled',
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
userPhoneNr: {
validators: {
notEmpty: {
message: 'Please insert phone nr'
},
regexp: {
regexp: /^[a-zA-Z0-9_]+$/,
message: 'Error'
}
}
},
}
}).on('success.form.fv', function(e, data) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="userProfilePhoto"]')[0].files;
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
if(data.status == 'success'){
getProfileData();
}
},
error: function(jqXHR, textStatus, errorThrown, data){
console.log(jqXHR, textStatus, errorThrown, data);
}
});
// Now Destroy
function destroyFormValidation() {
var instance = $('#rootwizard').data('formValidation');
if (instance) {
instance.destroy();
}
}
destroyFormValidation();
});
}
为什么您只能在第二次单击时更新,因为在第一次单击时,您实际上绑定了表单验证。为什么不在函数 updateProfile 之外单独绑定表单验证。
然后在更新配置文件中提交表单:
function updateProfile(){
$('#rootwizard').submit();
}
摆脱
if(geoLocationOK == 1){
updateProfile();
}else{
console.log("not ok");
e.preventDefault();
}
并将呼叫移至
updateProfile();
在你的里面
if (status === google.maps.GeocoderStatus.OK) { ... }
块。
您可能还需要在某处e.preventDefault();
(或者您可以将updateProfile
元素更改为不是提交按钮)。
看起来地理位置函数是异步的,这意味着它与其他代码并行执行。因此,您的if (geolocationOK == 1)
几乎肯定会在设置 geolocationOK 变量的函数之前运行。
在异步调用的任何此类情况下,如果您有依赖于异步调用结果的代码,则该调用必须在异步调用的"成功"上下文中执行。