我正在尝试从数据库中获取实时数据,但setTimeout无法正常工作,因此,如果我向数据库提交数据,则在刷新页面之前,它不会立即在刀片服务器(视图)中显示它们。如何在不刷新页面的情况下显示数据?
function getCount() {
$.ajax({
type: "GET",
url: '{{route('
live.review ')}}',
success: function(data) {
document.getElementById("mycount").innerHTML = getCount(3.6);
function getCount(rating) {
// Round to nearest half
rating = Math.round(data * 2) / 2;
let output = [];
// Append all the filled whole stars
for (var i = rating; i >= 1; i--)
output.push('<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i> ');
setTimeout(getCount, 1000);
// If there is a half a star, append it
if (i == .5) output.push('<i class="fa fa-star-half-o" aria-hidden="true" style="color: gold;"></i> ');
setTimeout(getCount, 1000);
// Fill the empty stars
for (let i = (5 - rating); i >= 1; i--)
output.push('<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i> ');
setTimeout(getCount, 1000);
return output.join('');
}
}
});
}
getCount();
答案 0 :(得分:0)
我认为您的问题是,您正在用内部getCount
函数遮盖外部getCount
函数,这意味着getCount
将作为回调传递给{{ 1}}是内部setTimeout()
,实际上并没有执行所需的Ajax调用,因此无法获取所需的数据。
为避免阴影变量可能引起的混乱,最佳实践被认为是通过对所有变量使用唯一值来避免任何变量阴影。我还删除了内部getCount
函数中的一些setTimeouts
,因为包括它们在内,并且实际上调用了您希望他们调用的函数,您将在以下位置多次调用ajax请求超时的结束,这对我来说没有意义,我也不认为那是您的本意。
我个人将按照以下方式重新编写这段代码:
getCount
本质上,我在这里所做的是,我完全删除了第二个const fetchCount = () => $.ajax({
type: "GET",
url: '{{route('
live.review ')}}',
success: function (data) {
// Round to nearest half
rating = Math.round(data * 2) / 2;
let output = [];
// Append all the filled whole stars
for (var i = rating; i >= 1; i--) {
output.push(
'<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i> '
);
}
// If there is a half a star, append it
if (i == .5) {
output.push(
'<i class="fa fa-star-half-o" aria-hidden="true" style="color: gold;"></i> '
);
}
// Fill the empty stars
for (let i = (5 - rating); i >= 1; i--) {
output.push(
'<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i> '
);
}
document.getElementById("mycount").innerHTML = output.join('');
setTimeout(fetchCount, 1000);
}
});
fetchCount();
函数声明,因为您只使用过一次该函数,并且在内部使用它。因此,所有这些处理逻辑都可以在函数的顶部进行,以防止以前发生的奇怪的提升。