所以我有一个从服务器返回的大型 JSON 对象,然后从中构建数据表并将其显示在表单上。这通常需要几秒钟..所以我在想一个加载栏。 我有加载栏背后的逻辑,但是构建 hmtl 数据的循环正在锁定浏览器,我无法调用我需要更新的元素。
这是我执行此操作的函数:
function buildDataTable(db_table, container_id) {
var $pb = $("<div id=\"progress-bar\"></div>");
$(container_id).html($pb);
$pb.progressbar({
value: 0
});
$.post("post location", {
view: "all"
}, function (data) {
var headers = "";
var contents = "";
var jsonObject = $.parseJSON(data);
var tik = Math.round(jsonObject.length / 100);
for (key in jsonObject[0]) {
headers += "<th>" + key.replace(" ", " ") + "</th>";
}
for (i in jsonObject) {
contents += "<tr>";
for (j in jsonObject[i]) {
contents += "<td class=\"border-right\">" + jsonObject[i][j] + "</td>";
}
contents += "</tr>";
if(Math.round(i/tik) == i/tik) {
/* if I run the alert (between popups) i can see the progressbar update, otherwise I see no update, the progressbar appears empty then the $(container_id) element is updated with the table i've generated */
alert('');
$pb.progressbar("value",i/tik);
}
}
var html = "<table cellpadding=\"5\" cellspacing=\"0\"><thead><tr>" + headers + "</tr></thead><tbody>" + contents + "</tbody></table>";
$(container_id).html(html);
$(container_id).children("table:first").dataTable({
"bJQueryUI": true,
"sScrollX": "100%"
});
});
}
最佳答案
[添加我的评论作为答案]
JavaScript 是单线程的。您必须将您的工作分解成多个部分并使用“setTimeout”按顺序调用它们,以允许 GUI 在处理过程中(在您的调用之间)更新,但即便如此,浏览器似乎仍然有些无响应。
关于javascript - 如何在 Javascript 中执行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6998330/