如果只有其中一个返回“未定义”,我无法将所有三个值(州、城市、邮政编码)设置为默认值(锡特卡、阿拉斯加、99801)。
我们在 Unbounce 页面构建器中使用此代码与 MaxMind 地理位置查找器。
$(window).on('load', function() {
$.getScript('//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js', function() {
geoip2.city(function(geoipResponse) {
let city = geoipResponse.city.names.en || 'Sitka'; // Default city to 'Sitka' if undefined
let state = geoipResponse.subdivisions[0].names.en || 'Alaska'; // Default state to 'Alaska' if undefined
let zip = geoipResponse.postal.code || '99801'; // Default zip to '99801' if undefined
$('#lp-pom-form-520 #State').val(state);
$('#lp-pom-form-520 #City').val(city);
$('#lp-pom-form-520 #Zip').val(zip);
}, function(error) {
console.error('Error fetching geoip data:', error);
});
});
});
我也尝试过这个,但没用:
<script>
$(window).on('load', function() {
$.getScript('//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js', function() {
geoip2.city(function(geoipResponse) {
let city = geoipResponse.city.names.en || 'Sitka';
let state = geoipResponse.subdivisions[0].names.en || 'Alaska';
let zip = geoipResponse.postal.code || '99801';
// Set default values if any of the fields is undefined
if (!city || !state || !zip) {
city = 'Sitka';
state = 'Alaska';
zip = '99801';
}
$('#lp-pom-form-520 #State').val(state);
$('#lp-pom-form-520 #City').val(city);
$('#lp-pom-form-520 #Zip').val(zip);
}, function(error) {
console.error('Error fetching geoip data:', error);
});
});
});
</script>
在第二次尝试中,您忘记在声明变量时删除默认值,这应该是:
let city = geoipResponse.city.names.en;
let state = geoipResponse.subdivisions[0].names.en;
let zip = geoipResponse.postal.code;
使用单行逻辑太复杂(排列太多),所以我会使用计数器来代替:
var U=0; // the counter
if(typeof state ==='undefined'){U++;}
if(typeof city ==='undefined'){U++;}
if(typeof zip ==='undefined'){U++;}
if(U==1){
city = 'Sitka';
state = 'Alaska';
zip = '99801';
} else {
}