Javascript 使用javascript获取国家代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35999265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:29:46  来源:igfitidea点击:

Get country code using javascript

javascriptjqueryhtmlsampleip-geolocation

提问by 702cs

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:

我不知道如何从访问我网页的访问者那里获取国家/地区代码。我看过很多其他的例子,但没有一个使用普通的 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>

I get the user's IP addrress from a JSONP request to ipinfo.iousing the $.getmethod of jQuery.

我从 JSONP 请求中获取用户的 IP 地址,以ipinfo.io使用$.getjQuery的方法。

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

不幸的是l2.io.js,此时不会返回除 ip 以外的任何内容。

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

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

回答by Xposedbones

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

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

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

回答by Mehnaz Saheb

I have used the below code using jQuery and its working fine for me. I am getting the country_code , country_name etc.,.

我已经使用 jQuery 使用了下面的代码,它对我来说工作正常。我正在获取 country_code 、 country_name 等。

 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);
    });
});

Note: Do remember to import the plugin script as below:

注意:请记住按如下方式导入插件脚本:

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

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