如何在xhttp对象从XML获取数据时显示进度计数器

How to show a progress counter while a xhttp object fetch data from XML?

本文关键字:数据 显示 计数器 获取 XML xhttp 对象      更新时间:2023-09-26

我有一个带有脚本的HTML页面,xhttp对象从XML文件中读取节点值并写入它们。在读取所有必需的节点之前,我希望显示一个以百分比(read_rows/total_rows * 100)表示的数字进度指示器。但由于整个过程都在一个线程上运行,我无法完成这一任务。对我该怎么做有什么建议吗?

以下是一些javascript代码-

function fetch(xml_file, index) {
    //create xhttp object, read xml, get nodeValue of element "VALUE" etc...
    xhttp = new XMLHttpRequest();
    xhttp.open("GET", xml_file ,false);
    xhttp.send(null);
    xmlDoc = xhttp.responseXML;
    data = xmlDoc.getElementsByTagName("VALUE")[index].childNodes[0].nodeValue;
    document.write(data);
    // CALCULATE PROGRESS AND WRITE TO SOME OVERLAY DIV...
}

以下是HTML-的一部分

<p><script>fetch(data_file, index); index++;</script></p>
<p><script>fetch(data_file, index); index++;</script></p>
<p><script>fetch(data_file, index); index++;</script></p>

当每个<p></p>都被填满时,我想在某个地方显示进度,比如叠加DIV。我如何同时做到这一点?

通过使用回调函数,我可以在xhttp对象从XML文件读取数据时显示进度。

我已将代码更改为-

function fetch(xml_file, index) {
    //create xhttp object, read xml, get nodeValue of element "VALUE" etc...
    xhttp = new XMLHttpRequest();
    xhttp.open("GET", xml_file ,false);
    xhttp.send(null);
    xmlDoc = xhttp.responseXML;
    data = xmlDoc.getElementsByTagName("VALUE")[index].childNodes[0].nodeValue;
    document.write(data);
    progress(index); //CALLBACK FUNCTION
}
function progress(index) {
    document.getElementById("ProgressString").innerHTML = Math.round((index/358)*100) + "% complete"; // 358 nodes were to be read
}