我的代码是
var api_url
$.getJSON("https://api.ipify.org/?format=json", function(e) {
myIP = e.ip;
//api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
});
//api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
function geoloc() {
api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
console.log(api_url)
const response = await fetch(api_url)
const data = await response.json();
console.log(data)
}
geoloc();我用Python3的http.server启动了它,它打印了"https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=undefined",不出所料,获取失败了。经过仔细检查,定义了变量myIP。我觉得这和async和await有关,但我不确定。
发布于 2020-04-13 05:39:40
https://jsfiddle.net/Lyjkzqcf/
您可以在$.getJSON()方法中调用geoloc()。请看下图:
var api_url
$.getJSON("https://api.ipify.org/?format=json", function(e) {
myIP = e.ip;
geoloc();
//api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
});
//api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
async function geoloc() {
api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
console.log(api_url)
const response = await fetch(api_url)
const data = await response.json();
console.log(data)
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
https://stackoverflow.com/questions/61178480
复制相似问题