I have a JSON object that is populated by an XHR. I then need to update that object with values from a separate XHR call. The issue I am running into is the second call isn't being made at the correct time and I think it's an issue with how I structured my object. Here is what I have:
function Proprietary()
{
var proprietary= this;
this.Groups = {};
this.getGroups = function()开发者_如何学运维
{
$.getJSON(group_url, function(data){proprietary.callReturned(data);});
}
this.callReturned = function(data)
{
//Do stuff
for(var i=0; i< data.groups.length; i++)
{
insparq.Groups[i] = data.groups[i];
$.getJSON(participant_url, function(p){proprietary.Groups[i].participants = p;});
}
//the function call below is the action I want to occur after the object is populated.
PopulateGroups();
}
};
There seem to be a number of weird things in that code snippet.
First of all, $.getJSON(...) takes a third parameter, which is your callback. The second parameter is data. I think you are passing a function as your data parameter. You will need to fix this in both places. If you don't need to pass anything, just have your second parameter be an empty object {}.
Here's one general way you can execute a callback after ALL of your XMLHttpRequests have come back from the server.
this.callReturned = function(data) {
var countdown = data.groups.length;
function callback() {
if(countdown-- === 1) {
PopulateGroups();
}
}
for(var i=0; i< data.groups.length; i++)
{
insparq.Groups[i] = data.groups[i];
$.getJSON(participant_url, { /* data to send to server */ }, callback);
}
}
In this snippet, the callback function is executed each time you get a XMLHttpRequest back from the server. The last one executes PopulateGroups(), after the countdown descends to 1 from data.groups.length.
精彩评论