问题一直是asked before,但是已经快四年了,也许有更好的解决方案。

我有一个$ .each循环,其中有时通过ajax获取其他数据。

我用获取的数据建立对象,循环后有一个从该对象生成HTML的函数。问题是循环在ajax数据到达之前完成。如果我在HTML生成功能中放置了警报,则内容正在正确加载。

我正在寻找一种仅在循环和所有ajax调用完成后才调用HTML-generator-function的解决方案。也许这是一种对启动的Ajax请求进行计数并等待所有请求完成的解决方案?

我相信jQuery延迟对我来说是正确的解决方案,但我只发现所有东西都停留在循环中的示例。有人可以帮忙吗?

我已将代码精简为最重要的内容:

//goes through each testplace -->main loop
$.each(jsobject, function(key, value)
{
 //build object together...
  for (var i = 0, numComputer = jenkinsComputer.contents.computer.length; i < numComputer; i++)
  {
    //If the testplace is in both objects then fire AJAX request
    if (jenkinsComputer.contents.computer[i].displayName == key) //<<<This can happen only once per $.each loop, but it does not happen every time
    {
      //next $.each-iteration should only happen when received the JSON
      var testplaceurl = jenkinsComputer.contents.computer[i].executors[0].currentExecutable.url;
      $.when($.getJSON("php/ba-simple-proxy.php?url=" + encodeURI(testplaceurl) + "api/json?depth=1&pretty=1")).done(function(jenkinsUser)
      {
        //build object together...
      });
    }
  }

}); //End of main Loop ($.each)
generateHTML(builtObject);


如果有人可以给我一些建议,那就太好了。

最佳答案

我会做这样的事情:

var thingstodo = $(jsobject).length;
var notfired = true;
$.each(jsobject, function(key, value)
{
 //build object together...
  for (var i = 0, numComputer = jenkinsComputer.contents.computer.length; i < numComputer; i++)
  {
    //If the testplace is in both objects then fire AJAX request
    if (jenkinsComputer.contents.computer[i].displayName == key) //<<<This can happen only once per $.each loop, but it does not happen every time
    {
      //next $.each-iteration should only happen when received the JSON
      var testplaceurl = jenkinsComputer.contents.computer[i].executors[0].currentExecutable.url;
      $.when($.getJSON("php/ba-simple-proxy.php?url=" + encodeURI(testplaceurl) + "api/json?depth=1&pretty=1")).done(function(jenkinsUser)
      {
        //build object together...
        thingstodo--;
        if(thingstodo === 0 && notfired){
            notfired = false;
            generateHTML(buildObject);
        }
      });
    }else{
        thingstodo--;
    }
  }

}); //End of main Loop ($.each)
if(thingstodo === 0 && notfired){
    generateHTML(buildObject);
}

09-11 20:48
查看更多