如何从API链接获取数据



如何从API链接获取数据

https://get.geojs.io/v1/ip/geo.js

我使用下面的代码,但不起作用。请大家谈谈我在这里做错了什么?

`

<div id="divIDClass"></div>
<script>
$.ajax({
url: 'https://get.geojs.io/v1/ip/geo.js',
success: function(data){
document.getElementById('divIDClass').innerHTML = data.country_code);
}
})
</script>

`

显示未定义的内部html

响应不是有效的JSON结构。当检查来自该端点的响应时,它返回一个格式为geoip({ /* data here */ })的字符串

如果你查看网站https://geojs.io,他们展示了一个如何使用它的例子。您需要创建一个名为geoip()的函数来接收JSON对象。在该函数中,您将能够处理响应。然后,您创建一个<script>标记,并将源设置为您请求的地址。当加载该脚本时,它会调用您的geoip()函数。

查看网站以了解如何使用它。

如果你仍然想自己提出请求,并且想要JSON格式的国家详细信息,你可以使用端点https://get.geojs.io/v1/ip/country.json(见文档(

示例:

$.ajax({
url: 'https://get.geojs.io/v1/ip/country.json',
success: (data, status, req) => {
// print the data in the console as it comes, to check on the structure
console.log(data);

// add it to the DOM
$('#response').html(`Country: ${data.name} (${data.country}/${data.country_3}), ip: ${data.ip},`);
},
error: (req, errorMessage) => console.error(errorMessage)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="response"></div>

好吧,因为它不是json,所以您应该使用文档中的示例https://www.geojs.io/:

<script type="application/javascript">
function geoip(json){
var userip      = document.getElementById("user_ip");
var countrycode = document.getElementById("user_countrycode");
userip.textContent      = json.ip;
countrycode.textContent = json.country_code;
}
</script>
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>

如果您仍然想使用ajax:

<script>
$.ajax({
url: 'https://get.geojs.io/v1/ip/geo.js',
success: function(data){
data = JSON.parse(data.slice(6,-1));
document.getElementById('divIDClass').innerHTML = data.country_code);
}
})
</script>

最新更新