加载类异步

时间:2016-03-09 10:01:03

标签: javascript jquery

我正在构建一个动态UI,我有一个“ul”列表需要从每个“li”的db加载一个值。一种显示数据库计数的徽章。

以下是一些代码:

function A {
    var count;
    function buildItem() {
        //some code to build a list "li" item
    };
    this.setCount = function(number) {
        count = number;
    };
    this.getHtml = function() {
        buildItem();
        return html;
    };
};

function B {
    var ul;
    var container = [];
    function loadCount(ref, i) {
        //ajax call that should set count for class A
        $.ajax({
            //blabla
            container[i].setCount(jsonResult);
        });
    };
    this.buildList = function() {
        //code that build the list..
    };
};

我需要的是loadCount()在解析脚本之前或同时分配从db检索的值。在显示列表后,使用异步请求填充计数。

如何使用从db获取的值并在显示整个列表后填充A类计数?

1 个答案:

答案 0 :(得分:0)

隐藏ul,直到收到所有li元素的计数。在加载期间显示装载程序。

var nResponses = 0;

$.ajax( "example.php" )

  .done(function(msg) {

     addLi(msg);                   //Add an li element to the ui

     if (liCount === nResponses)   //Check if all the responses are received. liCount is the number of lis you have
       showUl();                   //Everything is good. Show the ui  
     else
       nResponses++;               //Increase the response count  
  })