Javascript 我无法访问函数外部的局部变量
这是我的密码。我无法访问函数外部的局部变量,即使我在函数之前已初始化Javascript 我无法访问函数外部的局部变量,javascript,jquery,Javascript,Jquery,这是我的密码。我无法访问函数外部的局部变量,即使我在函数之前已初始化 <!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 getJSONRes
<!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>
var输出;
getJSONResult();
函数getJSONResult(){
jQuery.getJSON('https://isitup.org/nearhero.com.json,函数(数据){
输出=data.response\u代码;
alert(output);//它给出了输出405(我希望在函数之外)
});
}
警报(输出);//我无法在此访问输出405,其输出未定义
由于您没有异步使用此调用,我可能建议切换到$。ajax
,因为助手函数getJSON是一个巨大的PITA,几乎从未使用过。这将与您要查找的内容完全相同。:)
getJSONResult();
var输出;
函数getJSONResult(){
jQuery.ajax({
网址:'https://isitup.org/nearhero.com.json',
数据类型:“json”,
async:false,
成功:功能(数据){
输出=数据;
控制台日志(输出);
}
});
};代码>
尝试使用承诺
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);
});
非常确定它正在返回承诺对象。您需要查看承诺异步/等待。现在,它没有发出任何检查输出的警报您确定您收到过数据吗?是的,我确定。使用async后,我无法获取数据。请在这里结账