当我用控制台调用console.log(ip2db())时,它会输出“undefined”。如何返回从ip2db.php返回的值?
这是我的代码:
function ip2db(){
var result;
$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=a759dab4af1f462496dda90b3575f7c7', function(data) {
var ip_data = JSON.stringify(data, null, 2);
$.post("https://mywebsite.com/ip2db.php",
{
ip_data
},
function(data, status){
console.log("data: " + data + "
Status: " + status);
CreateUserStorage(data);
result = data;
}
);
});
return result;
}
ajax call are synchronic calls so you will never get a response. There two options: - passing a callback - use promises
await - async
but off-topic for this questionSo in this example you posted, you should do:
function ip2db(your_callback){
var result;
$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=a759dab4af1f462496dda90b3575f7c7', function(data) {
var ip_data = JSON.stringify(data, null, 2);
$.post("https://mywebsite.com/ip2db.php",
{
ip_data
},
function(data, status){
console.log("data: " + data + "
Status: " + status);
CreateUserStorage(data);
result = data;
your_callback(result)
}
);
});
}
you call it like this:
ip2db(function(result) {
console.log(result);
})
Tahtakafa, the http methods are async methods, meaning they do not continue flowing with the rest of the code as you would expect in the code you provided above. Thus when you execute ip2db, the value of result
at the end of the function is still undefined. However when the response from the server comes the value is set properly. So in order to get the correct value you need to understand async flow in js.
To solve your problem there are several options, but the one thing you need to know is to try to understand async operations in js.
function ip2db(){
return new Promise(function(resolve, reject){
$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=a759dab4af1f462496dda90b3575f7c7', function(data) {
var ip_data = JSON.stringify(data, null, 2);
$.post("https://mywebsite.com/ip2db.php",
{
ip_data
},
function(data, status){
console.log("data: " + data + "
Status: " + status);
CreateUserStorage(data);
result = data;
}
);
});
});
}
//use it like this
ip2db().then(function(){
});
function ip2db(){
$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=a759dab4af1f462496dda90b3575f7c7', function(data) {
var ip_data = JSON.stringify(data, null, 2);
$.post("https://mywebsite.com/ip2db.php",
{
ip_data
},
function(data, status){
console.log("data: " + data + "
Status: " + status);
CreateUserStorage(data);
// make use of result here to do any logic you might want to do
}
);
});
}
</div>