[英]cannot access javascript global variables
<html>
<head>
<title>Group Test</title>
<script type="text/javascript" src="/static/javascript/jquery-1.8.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
var global = new Array();
$.ajax({
url: "/json",
success: function(reports){
global = reports;
process(reports);
return global;
}
});
function process(reports){
for (i=0; i<reports.length; i++) {
document.write(i + " : "+reports[i].fields.report_name+"<br>");
}
}
</script>
</body>
</html>
好,所以有我的代碼。 我試圖在整個代碼中使用JSON數據,但是由於某些原因,每當我嘗試在$ .ajax()函數之外使用reports對象時,都會收到“ reports is undefined”錯誤。
根據JSLint的說法,代碼看起來不錯,並且AND將報告和變量global列為全局變量。
如果我嘗試運行任何使用這些外部條件之一的東西,它將無法正常工作。
'success'(reports)
global
global
line 22
process(reports)
global
document
您不能訪問reports
作為全局對象只有global
可以從每一個地方進行訪問。 reports
是成功以及process
功能的局部變量
<script type="text/javascript">
var global = new Array();
$.ajax({
url: "/json",
success: function(reports){
global = reports;
process(reports);
return global;
}
});
function process(reports){
for (i=0; i<reports.length; i++) {
document.write(i + " : "+reports[i].fields.report_name+"<br>");
}
}
// reports is undefined here. but global can be accessed (will be empty array before success function get called)
</script>
請記住, $.ajax
是異步的,因此,除非您在成功回調中調用函數,否則可能尚未設置該值。
另外,您還需要使用global
非reports
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.