我在从jQuery中获取国家代码时遇到了问题。
我可以使用IP获取用户信息。我想从中获取国家代码,并将其赋给一个变量,以便在函数中使用它。
下面是我使用的代码;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$.get("http://ipinfo.io", function(response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
</script>
</head>
<body>
<h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response:
<pre id="details"></pre>
</body>
</html>在这里,我想使用国家代码并赋值给一个变量。
发布于 2020-07-24 21:40:54
根据the documentation for ipinfo.io的说法,国家代码在响应中名为country的属性中。因此,您可以像访问ip、city和region一样访问它。
只需将该值赋给您变量:
$.get("http://ipinfo.io", function (response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
var countryCode = response.country; // <--- here
}, "jsonp");或者,如果您需要该函数作用域之外的值,则在该作用域中定义变量并在AJAX回调中设置它的值:
var countryCode = ''; // <--- here
$.get("http://ipinfo.io", function (response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
countryCode = response.country; // <--- and here
}, "jsonp");当然请注意,该值不会立即可用,直到AJAX操作完成后才可用。
https://stackoverflow.com/questions/63074208
复制相似问题