使用getJSON时未设置JavaScript中的全局变量? [英] Global variable in JavaScript not set when using getJSON?

查看:38
本文介绍了使用getJSON时未设置JavaScript中的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.如果我通过"google inspector"检查"pranks"变量,则一切正常.但是最后一行的警报"显示一个0大小的数组!我搞砸了本地/全局变量?

Here's my code. If i check "pranks" variable by "google inspector" all works fine. But the "alert" on the last line show a 0-size array! I mucking with local/global variables?

<script type="text/javascript">
(function() { 

 pranks = [];

function getAllPranks(){


    $.getJSON('list.json', function(data) {

      $.each(data['pranks'], function(key, val) {
        pranks.push(val);
      });

    });

}

 $(document).ready(function(){


    getAllPranks();

    alert(pranks.length);

 });


 }());
 </script>

推荐答案

接受代码:

<script type="text/javascript">
(function() { 
    function getAllPranks( callback ) {
        $.getJSON('list.json', function(data) {
            $.each(data['pranks'], function(key, val) {
                pranks.push(val);
            });
            callback( pranks );
        });
    }

    $(document).ready(function(){
        getAllPranks( function( pranks ) {
            alert(pranks.length);
        } );
    });
}());
</script>

$.getJSON 是异步的.这意味着一旦返回结果,便会执行回调函数( function(data)).当您执行 alert(pranks.length)时,该函数未执行,因为此时响应尚未返回.

$.getJSON is asynchronous. This means the callback function (function(data)) is executed once the result comes back. When you execute alert(pranks.length), the function has not executed because the response hasn't come back at this moment.

这篇关于使用getJSON时未设置JavaScript中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆