我有一个要处理的事项列表,我在调用服务器端脚本时更新了它们的状态。我做了这个函数调用,递归调用脚本,以便顺序执行调用,避免任何关于更新内容的混淆,但它似乎不优雅,我担心如果列表中有太多项目,它可能会占用内存。
有没有更好的方法来解决这个问题?
multiXHR.pageToUpdate.html
<head>
<title>Test Multi XHR</title>
<script type="text/javascript">
var listArray = ["1","2","3","4","5"];
var currentStatus = 0;
function doSeveralThings(index) {
currentStatus=index;
status = "status" + index;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status==200) {
document.getElementById(status).innerHTML = "done";
currentStatus++;
if (currentStatus<listArray.length) {
doSeveralThings(currentStatus);
}
} else {
document.getElementById(status).innerHTML = "[error: " + xmlhttp.statusText + ", readyState: " + xmlhttp.readyState + ", status: " + xmlhttp.status +"]" ;
}
} else {
document.getElementById(status).innerHTML = "[processing]";
}
}
xmlhttp.open("GET", "multiXHR.doOneThing.php?thisItemNumber=" + currentStatus, true);
xmlhttp.send();
}
function makeList() {
for(index=0; index< listArray.length; index++) {
listItemSpan = "<span>" + " "+ index + ": " + "<a id='status" + index + "' style='color:black'>[queued]</a></span><br>";
document.getElementById("listToProcess").innerHTML += listItemSpan;
}
}
</script>
</head>
<body>
<p>
List To Process:<br />
<span id="listToProcess"></span>
</p>
<p>
Process: <button onclick="doSeveralThings(0)">Go</button>
</p>
<script type="text/javascript">
makeList();
</script>
</body>
multiXHR.doOneThing.php
<?php
$returnVal = $_SESSION["thisItemNumber"];
sleep(1); # pretend to do something that takes time
echo($returnVal);
?>