$.getJSON 调用中的 JavaScript 变量作用域

标签 javascript jquery scope getjson

为什么调用 showOrders 时订单数组为空?我的服务返回 4 个对象,我可以在 .push 调用中完成项目初始化,但返回的数组始终为空。

var showOrders = function(orders){
    $.each(orders, function(i, val){

        alert(val.Order + "::" + val.Href);         

    });
}
var orders = (function(d){
    var _r = [];
    $.getJSON("/_vti_bin/listdata.svc/Orders", function (data) {
        for(var i = 0; i < data.d.results.length; i++)
        {
            var o = data.d.results[i];

            _r.push({
                    Id: o.Id,
                    Order: o.Order, 
                    PurchaseDate: o.PurchaseDate, 
                    CustomerPO: o.CustomerPO, 
                    PurchasedBy: o.PurchasedBy, 
                    SubTotal: o.SubTotal, 
                    Status: o.Status,
                    Href: o.Path + "/DispForm.aspx?ID=" + o.Id
            });
        }
        return _r;
    });
    d(_r);
})(showOrders);  

最佳答案

$.getJSON 正在执行异步调用。您需要在 getJSON 调用的回调内执​​行 d 回调(在循环之后):

var orders = (function(d){
  var _r = [];
  $.getJSON("/_vti_bin/listdata.svc/Orders", function (data) {
      for(var i = 0; i < data.d.results.length; i++)
      {
          var o = data.d.results[i];

          _r.push({
                Id: o.Id,
                Order: o.Order, 
                PurchaseDate: o.PurchaseDate, 
                CustomerPO: o.CustomerPO, 
                PurchasedBy: o.PurchasedBy, 
                SubTotal: o.SubTotal, 
                Status: o.Status,
                Href: o.Path + "/DispForm.aspx?ID=" + o.Id
        });
      }
      d(_r);

  });

})(showOrders);  

关于$.getJSON 调用中的 JavaScript 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14647987/

相关文章:

javascript - 如何将 hover css 与圆形图像一起使用?

javascript - 在以下代码中替代全局变量

javascript - 如何将 Raphael Canvas 整个(包含一些对象)从一个坐标连续移动到另一个坐标到另一个坐标

javascript - jQuery.ajax() 成功回调有未定义的参数

javascript - 如何从表单发送邮件并显示弹出窗口

Python 博客 RSS 提要将 BeautifulSoup 输出抓取到 .txt 文件

javascript - 查找从一个集合到另一个集合的重复对象 - 在knockout JS中使用2个数组

具有 id 的可见元素的 jQuery 选择器

Javascript,回调函数中的变量范围之外?

javascript - 将 JavaScript 变量添加到本地范围