使用javascript获取国家代码 [英] Get country code using javascript

查看:344
本文介绍了使用javascript获取国家代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't figure out how to get a country code from a visitor that goes to my webpage. I have seen plenty of other examples but none use plain Javascript. Here is my current code:

<!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 地址.

I get the user's IP addrress from a JSONP request to ipinfo.io using the $.get method of jQuery.

不幸的是,l2.io.js 目前除了 ip 之外没有返回任何东西.

Unfortunately l2.io.js does not return anything other then the ip at this time.

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

If anyone can help or has any examples please link all related JavaScript libraries that will be needed. Thanks.

推荐答案

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

According to the docs on the website, you should be able to retrieve the country code with ipinfo. try using $.getJSON instead of $.get

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

这篇关于使用javascript获取国家代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆