我们可以通过调用第三方API服务来获取访客的IP地址。以下是一个简单的示例代码:
<script>
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
console.log(`Your IP address is ${data.ip}`);
// 在页面上显示IP地址
document.getElementById('ip-address').textContent = data.ip;
})
.catch(error => console.error(error));
</script>
<p id="ip-address"></p>
在这个例子中,我们使用fetch()
方法调用ipify.org的API接口,并将返回的JSON数据解析出IP地址,将其显示在页面上。
除使用第三方API,我们还可以利用HTML5提供的Geolocation API来获取访客的IP地址。这个方法可以直接从浏览器获取IP地址信息,无需依赖第三方服务。以下是示例代码:
<script>
navigator.geolocation.getCurrentPosition(
position => {
console.log(`Your IP address is ${position.coords.ip}`);
// 在页面上显示IP地址
document.getElementById('ip-address').textContent = position.coords.ip;
},
error => console.error(error)
);
</script>
<p id="ip-address"></p>
在这个例子中,我们使用navigator.geolocation.getCurrentPosition()
方法来获取访客的IP地址信息,并将其显示在页面上。不过需要注意的是,并不是所有浏览器都支持这个API,使用时需要进行兼容性检查。