1

为什么调用 showOrders 时,orders 数组是空的?我的服务返回 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);  
4

1 回答 1

3

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

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);  
于 2013-02-01T14:31:06.393 回答