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);
如何从异步函数中获取变量才能变为全局?
答案 0 :(得分:2)
试试这个,这是好方法
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);
}
答案 1 :(得分:0)
我明白了。我让ajax函数不像这样异步:
type RawText = String
-- [Char] 'a','b','c','d','e'
type SingleWord = String
type Line = [SingleWord]
type Page = [Line]
-- [-------CHAR-----]
-- split " one two three ff " = ["one","two","three","ff"]
-- [char],[char],[char],[char]
-- " " is delimiter for a []
split' :: RawText -> [SingleWord]
spilt' [] = []
split' xs
| xs == [] = []
| isBlank (head xs) = split' xs
| otherwise = waitForBlank xs : spilt' (tail xs)
isBlank :: Char -> Bool
isBlank x = if x == ' ' then True else False
waitForBlank :: String -> String
waitForBlank [] = []
waitForBlank (x:xs)
| isBlank x = []
| otherwise = x : waitForBlank xs
答案 2 :(得分:0)
在声明要成为全局的变量时不要使用var