javascript - 使用javascript获取国家代码

标签 javascript jquery html sample ip-geolocation

<分区>

我不知道如何从访问我网页的访问者那里获取国家/地区代码。我看过很多其他示例,但没有一个使用纯 Javascript。这是我当前的代码:

<!DOCTYPE html>
<html lang="en-US">
<head>
</head>
<body>
    <script type="text/javascript">
        var userip;
    </script>
    <script type="text/javascript" src="https://l2.io/ip.js?var=userip">       </script>

    <script type="text/javascript">
        document.write("IP: ", userip);

        $.get("http://ipinfo.io/"+userip.text(), function (response) {
            reg.text("country code here" + response.country);
        }, "jsonp");
    </script>
</body>
</html>

我使用 jQuery 的 $.get 方法从对 ipinfo.io 的 JSONP 请求中获取用户的 IP 地址。

不幸的是 l2.io.js 此时除了 ip 之外没有返回任何东西。

如果有人可以提供帮助或有任何示例,请链接所有需要的相关 JavaScript 库。谢谢。

最佳答案

根据网站上的文档,您应该可以使用 ipinfo 检索国家代码。尝试使用 $.getJSON 而不是 $.get

var country_code = null;
$.getJSON('http://ipinfo.io/' + userip, function(data){
    country_code = data.country;
    alert(country_code);
});

关于javascript - 使用javascript获取国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999265/

相关文章:

html - 如何将文本居中放置在div的中心

javascript - 单击按钮时,如何在发送 ajax 之前调用验证函数?

javascript - jquery 在 .on 内运行条件验证

javascript - 自动化一系列类似的操作

javascript - 将 String 对象转换为 Json 对象

html - Bootstrap 子菜单拉伸(stretch)全屏并覆盖整个页面

javascript - $.fn.dataTableExt.aoFeatures.push 更改设置

javascript - 提交时跳转到 anchor

javascript - 在 MediaElement Player 中动态添加播放列表项

html - md-select 箭头颜色变化