为什么调用 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/