我有一个奇怪的问题,我想从IP获取国家代码(比如美国的US),我需要使用免费的API,所以我找到ipify for IP(运行良好)并尝试使用geoplugin作为国家代码,这是我的代码:
$.getJSON('https://api.ipify.org/?format=json', function(r){
alert(r.ip);
$.getJSON('http://www.geoplugin.net/json.gp?ip=' + r.ip + "jsoncallback=?", function(y) {
alert(y.geoplugin_countryCode);
});
});
IP显示在警报中,就像我想要的那样但是geoplugin JSON存在问题,它在浏览器中显示错误:Uncaught SyntaxError: Unexpected token :
就像它在JSON中发现错误并且它试图运行代码(改变了我的IP):https://gyazo.com/c96a9aa50ac1d886b37b95b583e1415e
答案 0 :(得分:1)
在这里!以下代码段成功记录国家/地区代码。
所以用以下代码片段替换你的代码,我使用AJAX来实现你的目标:
$.ajax({
url : 'https://api.ipify.org/?format=json',
dataType : 'JSON',
success : function(data) {
alert( data.ip );
$.ajax({
url : 'http://www.geoplugin.net/json.gp?' + data.ip + '&jsoncallback=?',
dataType : 'JSON',
success : function(data) {
alert( data.geoplugin_countryCode);
//you can print variable: "data" as well, or any property as data.someProperty
},
error : function(error) {
console.log("Could not get information: " + error);
}
});
},
error : function(error) {
console.log("Could not get information: " + error);
}
});
享受!
答案 1 :(得分:0)
更新如下
$.getJSON('https://api.ipify.org/?format=json', function(r){
$.getJSON('http://www.geoplugin.net/json.gp?ip=' + r.ip, function(y){
alert(y.geoplugin_countryCode);
});
});
您可以使用其他方法。在页面中添加脚本
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script type="text/javascript">
alert(geoplugin_countryCode());
</script>