使用 JavaScript 根据 IP 获取访问者国家/地区

get visitors country on IP based using JavaScript

我想使用 javascript 根据他们的 IP 获取访问者所在的国家/地区。我对 html 代码进行了一些更改。我在 Whosebug 上找到了一段代码,效果很好,但我不知道如何从数组中提取国家/地区。

代码

$.get("https://api.ipdata.co", function (response) {
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="response"></pre>

我想要的:

我的 html 页面上有定价 table,现在我只想根据访问者所在的国家/地区更改价格符号。

非常感谢任何帮助。

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

检查这是否有效:

$.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>