簡體   English   中英

無法訪問javascript全局變量

[英]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是異步的,因此,除非您在成功回調中調用函數,否則可能尚未設置該值。

另外,您還需要使用globalreports

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM