如何使用javascript基于IP地址获取用户位置?

时间:2018-03-27 17:29:40

标签: javascript html css

如何使用javascript基于IP地址获取用户位置?如果用户来自其他国家/地区,如何显示复选框,如果用户不是来自其他国家/地区,则隐藏该复选框?

1 个答案:

答案 0 :(得分:0)

您可以使用ipapi API

获取用户的国家/地区名称

https://ipapi.co/json/

响应

{
    "ip": "103.209.196.6",
    "city": "Dhaka",
    "region": "Dhaka Division",
    "region_code": "C",
    "country": "BD",
    "country_name": "Bangladesh",
    "continent_code": "AS",
    "postal": "1000",
    "latitude": 23.7231,
    "longitude": 90.4086,
    "timezone": "Asia/Dhaka",
    "utc_offset": "+0600",
    "country_calling_code": "+880",
    "currency": "BDT",
    "languages": "bn-BD,en",
    "asn": "AS134180",
    "org": "Md. Shariful Islam T/A BRISK SYSTEMS"
}

所以从回复中你得到country_code和country_name你可以使用country_code / country_name。

代码



$.getJSON('https://ipapi.co/json/', function(result) 
{
   $("input[name='country']").each( function () 
   {
     if(result.country_name ==$(this).val())
     {
        $(this).parent().hide();
      }
   }
)});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div >
    <label><input type="checkbox" name="country" value="United States"> United States</label>
    <label><input type="checkbox" name="country" value="Bangladesh">Bangladesh</label>
</div>
&#13;
&#13;
&#13;

相关问题