如何使用简单的 Javascript 检测访问者国家/地区

How to detect visitor country using simple Javascript

此代码不适用于 squarespace,有人可以识别此代码有什么问题吗?但是,它在 jsfiddle 上工作。

<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>


<script>
 jQuery(document).ready(function($) {
    jQuery.getScript('http://www.geoplugin.net/javascript.gp', function() 
    {
        var country = geoplugin_countryName();
        alert(country);
        var code = geoplugin_countryCode();
        alert(code);
        console.log("Your location is: " + country + ", " + zone + ", " + district);
    });
});</script>

变量“zone”和“district”没有定义,删除它们就可以了,使用这个:

<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
    jQuery(document).ready(function ($) {
        jQuery.getScript('http://www.geoplugin.net/javascript.gp', function () {
            var country = geoplugin_countryName();
            alert(country);
            var code = geoplugin_countryCode();
            alert(code);
            console.log("Your location is: " + country);
        });
    });
</script>

我已经添加了缺少的区域和城市代码,试试这个现在可以用了,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function($) {
    jQuery.getScript('http://www.geoplugin.net/javascript.gp', function() 
    {
        const country = geoplugin_countryName();
        const countryCode = geoplugin_countryCode();
        const city = geoplugin_city();
        const region = geoplugin_region();
        console.log(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`);
        alert(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`)
    });
});

更新:-

由于上述插件是通过 HTTP 托管的并且出现错误,这是替代解决方案,

fetch('https://extreme-ip-lookup.com/json/')
  .then(res => res.json())
  .then(res => {
    console.log(res);
    document.getElementById('target').innerHTML = `Your location is: ${res.city}, ${res.region}, ${res.country}`;
  })
  .catch((data, status) => {
    console.log('Request failed');
  })