JSON 对象 XHR 和闭包
我有一个由 XHR 填充的 JSON 对象。然后,我需要使用单独的 XHR 调用中的值更新该对象。我遇到的问题是第二次调用没有在正确的时间进行,我认为这是我如何构造对象的问题。这是我所拥有的:
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();
}
};
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();
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码片段中似乎有很多奇怪的东西。
首先, $.getJSON(...) 采用第三个参数,这是您的回调。第二个参数是数据。我认为您正在传递一个函数作为数据参数。您需要在两个地方修复此问题。如果您不需要传递任何内容,只需将第二个参数设置为空对象 {} 即可。
这是在所有 XMLHttpRequest 从服务器返回后执行回调的一种通用方法。
在此代码片段中,每次从服务器返回 XMLHttpRequest 时都会执行回调函数。最后一个执行 PopulateGroups(),在倒计时从 data.groups.length 减到 1 后。
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.
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.