jQuery中的全局变量声明

时间:2013-07-01 12:32:24

标签: javascript jquery global-variables

我有这个代码,我想让变量表成为一个全局变量,但它不起作用,我不明白为什么,有人可以帮助我吗?

      var table;
      function formatCustomerResults(obj) {
            var rows = Array();
            for (i = 0; i < obj.length; i++) {
                var item = obj[i];
                rows.push({
                    cell : [ item.guid, item.limittime, item.limitname ]
                });
            }

            console.log(rows);
            table = rows;

            return {
                total : obj.length,
                page : 1,
                rows : rows
            };
        }

        $.ajax({
            type : 'GET',
            url : 'http://localhost:6181/fintpWebServices/api/timelimits',
            dataType : 'json',
            success : function(data) {
                obj = data.timelimits;
                formatCustomerResults(obj);
            }
        });

         console.log(table);

4 个答案:

答案 0 :(得分:2)

你正在进行异步调用,你表现得像是同步的。在回调被触发之前,您正在调用console.log()。 Ajax 101的东西。

答案 1 :(得分:0)

您的问题是您正在致电

console.log(table);
之前的

实际上是由您的AJAX调用和 formatCustomerResults 函数填充的。请记住,AJAX的'A'代表'异步'。

答案 2 :(得分:0)

实际上,在变量更新之前设置了表变量,因为 使用asynchronous

后,此代码为ajax

如果您在致电consoleformatCustomerResults,则会显示您的table

        success : function(data) {
            obj = data.timelimits;
            formatCustomerResults(obj);
            console.log(table);// this will print data
        }

答案 3 :(得分:-1)

我认为您显示的代码是由更大的函数包装的?这可以解释为什么它被在本地而不是全球宣布。

要确保变量始终全局声明,只需将其定义为窗口对象的属性,因此删除行

var table;

并替换

table = rows;

window.table = rows;

您也可以简单地写

table = rows;

没有将表声明为局部变量,但是将全局变量显式定义为窗口对象的属性(这是全局变量是什么)是一种很好的做法,以便读者清楚你对全局变量的定义是有意的。