var position= $.getJSON( "http://ip-api.com/json", function( data ) {
position = {lon: data.lon, lat: data.lat}
return position;
});
var lon = position.lon;
var lat = position.lat;
console.log(lon);
How can I getvariables from async functions to become global?
如何从异步函数变为全局变量?
3 个解决方案
#1
2
Try this, this is work good way
试试这个,这是好方法
window.onload = function() {
set();
setTimeout(get,2000);;
};
function set() {
$.getJSON( "http://ip-api.com/json",function(data) {
var position = {"lon": data.lon,"lat": data.lat};
document.getElementById("id").value= position;
});
}
function get() {
var k = $("#id").val();
console.log(k);
}
#2
0
I figured it out. I made the ajax function to not be async like this:
我想到了。我让ajax函数不像这样异步:
$.ajax({
async: false,
url: "http://ip-api.com/json",
success: function(data) {
console.log(data);
position = { lon: data.lon, lat: data.lat };
}
});
#3
0
don't use var when declaring variables that you you want to be global
在声明要使用全局变量的变量时,请不要使用var
#1
2
Try this, this is work good way
试试这个,这是好方法
window.onload = function() {
set();
setTimeout(get,2000);;
};
function set() {
$.getJSON( "http://ip-api.com/json",function(data) {
var position = {"lon": data.lon,"lat": data.lat};
document.getElementById("id").value= position;
});
}
function get() {
var k = $("#id").val();
console.log(k);
}
#2
0
I figured it out. I made the ajax function to not be async like this:
我想到了。我让ajax函数不像这样异步:
$.ajax({
async: false,
url: "http://ip-api.com/json",
success: function(data) {
console.log(data);
position = { lon: data.lon, lat: data.lat };
}
});
#3
0
don't use var when declaring variables that you you want to be global
在声明要使用全局变量的变量时,请不要使用var