1

我每 5 秒执行一次以下代码,但内容一次显示为一个块,理想情况下它应该在每次循环时写入 DOM?那么数组中的每个值都应该有自己的 div 吗?

function newfunction() {
    var obj;
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            obj = JSON.parse(xmlhttp.responseText);

            for (var i = 0, n = obj.length; i < n; i++) {
                var divTag = document.createElement("div");
                divTag.id = "div" + i;
                divTag.innerHTML = obj[i];
                divTag.className+="nodeclass";
                document.getElementById("content").appendChild(divTag);
            }
        }
    }
    xmlhttp.open("GET","verify.php",true);
    xmlhttp.send();
}
window.onload=function() {
    newfunction();
    setInterval("newfunction()",5000);
}

所以在页面加载时它会获得一些内容,然后它应该每 5 秒添加更多内容。

谢谢。

4

2 回答 2

1

我没有看到任何 setTimeout 或 setInterval,但我会这样做:

function processIt(obj, i) {
    var n = obj.length;
    if (i < n) {
        var divTag = document.createElement("div");
        divTag.id = "div" + i;
        divTag.innerHTML = obj[i];
        divTag.className+="nodeclass";
        document.getElementById("content").appendChild(divTag);
        setTimeout(function () {
            processIt(obj, ++i);
        }, 1000);
    }
}

var obj = document.getElementsByTagName("div"); // Or whatever "obj" is

processIt(obj, 0);
于 2012-08-22T17:56:40.953 回答
0

Updated my answer as you just updated your snippet.. What does your JSON-object from verify.php look like? Is it an object or an array or simple strings?

function retrieveContent() {
    var arrayOfElements,
        xmlhttp;

    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            arrayOfElements = JSON.parse(xmlhttp.responseText);
            insertElements(arrayOfElements);

            setTimeout(retrieveContent, 5 * 1000);
        }
    };

    xmlhttp.open("GET","verify.php",true);
    xmlhttp.send();
}

function insertElements(arrayOfElements) {
  var divTag,
      i,
      n;

  for (i = 0, n = arrayOfElements.length; i < n; i++) {
    divTag = document.createElement("div");
    divTag.id = "div" + i;
    divTag.innerHTML = obj[i];
    divTag.className+="nodeclass";
    document.getElementById("content").appendChild(divTag);
  }
}

window.onload=retrieveContent;

jsbin snippet

于 2012-08-22T17:58:33.447 回答