如何在以下代码中将JSON结果传递给全局变量?我已经试过使用return来获取它,但是不起作用。我有一个空物体。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var astrosObj = {};
fetch('http://api.open-notify.org/astros.json').then(function(response){
return response.json();
}).then(function(obj){
//console.log('Obj: ', obj);
astrosObj = obj;
return astrosObj;
}).catch(function (error){
console.error('Json retrieve error');
console.error(error);
});
console.log(astrosObj);
</script>
</body>
</html>
谢谢!