使用JavaScript获取基于IP的访问者国家/地区

时间:2018-05-06 15:32:28

标签: javascript frontend currency

我希望使用javascript根据他们的IP获取访问者国家/地区。我在我的HTML代码中做了一些更改。我在stackoverflow上找到了一些代码,它运行良好,但我不知道如何从数组中提取国家。

代码

cannot read property 'name' of undefined

我想要的是什么:

我的html页面上有一个定价表,现在我只想根据访客的国家/地区更改价格符号。

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

如何使用fetch并完全避免使用jQuery?

fetch('https://api.ipdata.co')
.then(res => res.json())
.then(data => console.log(data.country_code));

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch

编辑:将ID为response的元素的文本值更改为返回的货币符号。

fetch('https://api.ipdata.co')
.then(res => res.json())
.then(data => {
    document.querySelector('#response').textContent = data.currency.symbol;
});

答案 1 :(得分:-1)

检查是否有效:

$.get("https://api.ipdata.co", function (response) {
    $("#response").html(response.currency.symbol);
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="response"></pre>
相关问题