我想追加一个元素并立即更新。 console.log()按预期显示数据,但append()在for循环完成之前不执行任何操作,然后立即将其全部写入。
的index.html:
...
<body>
<p>Page loaded.</p>
<p>Data:</p>
<div id="Data"></div>
</body>
test.js:
$(document).ready(function() {
for( var i=0; i<5; i++ ) {
$.ajax({
async: false,
url: 'server.php',
success: function(r) {
console.log(r); //this works
$('#Data').append(r); //this happens all at once
}
});
}
});
server.php:
<?php
sleep(1);
echo time()."<br />";
?>
直到for循环完成后,页面才会呈现。在运行javascript之前,它至少应该首先呈现HTML吗?
答案 0 :(得分:3)
如果您切换到async: true
,则屏幕将能够在您追加数据时进行更新。
$(document).ready(function() {
var cntr = 0;
// run 5 consecutive ajax calls
// when the first one finishes, run the second one and so on
function next() {
$.ajax({
async: true,
url: 'server.php',
success: function(r) {
console.log(r); //this works
$('#Data').append(r); //this happens all at once
++cntr;
if (cntr < 5) {
next();
}
}
});
}
next();
});
如果您坚持使用async: false
(这通常很糟糕),那么您可以在每个ajax调用之间放置一个短setTimeout()
,并且屏幕会在超时期间更新。
还有一些黑客“可能”通过访问某些CSS属性导致屏幕更新(无保证),这些属性只能在HTML布局是最新的时才能计算出来,这可能会导致浏览器显示最新的变化。我说“可能”,因为这不是规范,只是在一些浏览器中观察行为。您可以阅读有关this option here的更多信息。
在任何情况下,由于您已经在使用ajax调用,因此在这里解决此问题的最佳方法是使用async: true
并将循环结构更改为将使用async ajax调用的结构(就像我'在我的例子中显示了。)