这是我的代码。即使在函数之前进行了初始化,我也无法访问函数外部的局部变量。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var output;
getJSONResult();
function getJSONResult(){
jQuery.getJSON( 'https://isitup.org/nearhero.com.json', function( data ) {
output = data.response_code;
alert(output); // It gives output 405 (that i want outside the function)
});
}
alert(output); // I am not able to access output 405 here and its gives output undefined
</script>
</head>
<body>
</body>
</html>
答案 0 :(得分:1)
尝试使用Promise
var output;
function getJSONResult(){
return new Promise((resolve,reject) => {
jQuery.getJSON( 'https://isitup.org/nearhero.com.json', function( data ) {
result = data.response_code;
resolve(result);
});
});
}
getJSONResult().then((result) => {
output = result;
alert(result);
});
答案 1 :(得分:0)
由于您不是异步使用此调用,因此我建议您切换到$.ajax
,因为辅助函数getJSON是一个巨大的PITA,几乎从未使用过。这将做您想要的相同的事情。 :)
getJSONResult();
var output;
function getJSONResult() {
jQuery.ajax({
url: 'https://isitup.org/nearhero.com.json',
dataType: 'json',
async: false,
success: function(data) {
output = data;
console.log(output);
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>