在我的javascript中,我使用Jquery 1.7.2和ajax来获取一些数据,然后将其显示在页面中。 因为我已经阅读了很多关于jquery延迟对象的好东西并且确信它将解决我当前的要求。它几乎只有一个故障! 说到这一点,我在我的一个函数中得到数组作为参数。这个数组包含客户的所有ID。我需要根据此ID让每个客户与每个客户相关联。 问题是当我为cusomter数组使用for循环时,它总是比数组的大小少1次。例如,如果我有5个客户,它只运行4次并获得他们各自的网站。我已尝试使用不同的数据集,结果是相同的。(每次少一个)。
下面是我的代码,我已经对我的代码发表评论以便更好地理解。请看一下,告诉我在这里我很遗憾的是什么。
function GetCustSites(CustArray)
{
// this routine will get all the sites belongs to each customer from passed CustArray.
var oDataSelectQuery = "";
var SiteArrayDefd = [];
var SiteCollection = [];
for(var i = 0; i< CustArray.length;i++) // for loop for each customer
{
var CustomerID = CustArray[i].CustomerId
if(CustomerID != null && CustomerID != "")
{
oDataSelectQuery = query to rest endpoint where custeomrid eq = CustomerID ;
}
SiteArrayDefd.push(GetSites(oDataSelectQuery));
// passing the oData query to another function for each customer
// and storing the returned deferred object in array(SiteArrayDefd)
}
// Loop thru the ajax deferred obeject and get the data returned by query
$.when.apply($,SiteArrayDefd).then(function()
{
for(var k = 0; k < SiteArrayDefd.length; k++) // looping thru each deferred object
{
// alert(k);
// there are 7 customers but above for loop runs for only 6. alerting k doesn't even show 6. it's alway 1 customer less and code goes to the next execution.
SiteArrayDefd[k].done(function(data,textStatus,XmlHttpRequest) // object in resolved state
{
if(data.d.results.length > 1) // if more then 1 site comes back from the query
{
for(var j=0; j < data.d.results.length; j++)
{
SiteCollection.push(data.d.results[j]);
}
}
else if (data.d.results.length == 1) // if only one site comes back from the query
{
SiteCollection.push(data.d.results[0]);
}
else
{
alert('No site exist');
}
});
}
ProcessSite(SiteCollection)
// assume by this statement all the above ajax calls are resolved and 'SiteCollection' should have sites of all
// the customers but for somehow it only runs for 1 time less. I have tested with multiple record sets but alll
// the time it takes 1 custome less which is not always the last customer in the array.
});
}
function GetSites(oDataSelect)
{
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataSelect ,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); }
});