![](/img/trans.png)
[英]I am not able to access the globally declared variable, on which I am performing an operation in a function, outside the function scope
[英]I am not able to access local variable outside function
這是我的代碼。 即使我在 function 之前初始化,我也無法訪問 function 之外的局部變量。
<!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>
嘗試使用 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);
});
由於您沒有異步使用此調用,我可能建議切換到$.ajax
作為助手 function 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.