使用JS + ipapi.co确定用户位置
知识点:JS获取数据、判断
注意
使用该方法最多实现市级定位。
网页中
你可以在你的网页中添加一段内容,例如:
html
<p id="contentForXiamen" style="display:none;">老乡啊?!有空一起玩呀。</p>JS部分
接下来,正式开始编写JS代码,放在前面提到的代码的后面,使用<script></script>标签包起来。
javascript
// 判断用户所在地区
// 示例判断地址:厦门市(福建省)
fetch('https://ipapi.co/json/') // 服务器
.then(response => response.json())
.then(data => {
const city = data.city;
if (city === 'Xiamen') { // 如果是老乡
document.getElementById('contentForXiamen').style.display = 'block';
console.log('都是厦门的啊?!欢迎欢迎!')
} else { // 如果不是
console.log('欢迎来自' + city + '的访客!');
}
})
.catch(error => console.error('[ERROR]', error));// 如果出错完整代码
就结束了,简单不?
html
<p id="contentForXiamen" style="display:none;">老乡啊?!有空一起玩呀。</p>
<script>
// 判断用户所在地区
// 示例判断地址:厦门市(福建省)
fetch('https://ipapi.co/json/') // 服务器
.then(response => response.json())
.then(data => {
const city = data.city;
if (city === 'Xiamen') { // 如果是老乡
document.getElementById('contentForXiamen').style.display = 'block';
console.log('都是厦门的啊?!欢迎欢迎!')
} else { // 如果不是
console.log('欢迎来自' + city + '的访客!');
}
})
.catch(error => console.error('[ERROR]', error));// 如果出错
</script>其他示例
自动欢迎各地访客:
html
<p>欢迎来自 <span id="city">[加载中...]</span> 的访客。</p>
<script>
// 判断用户所在地区
fetch('https://ipapi.co/json/') // 服务器
.then(response => response.json())
.then(data => {
const city = data.city;
const CityWelcome = document.getElementById("city");// 获取要替换的文本元素
CityWelcome.textContent = city;
console.log('欢迎来自' + city + '的访客!');
})
.catch(error => console.error('[ERROR]', error));// 如果出错
</script>