Jquery推荐旋转器Ajax功能提前运行
我正在为我的网站使用 Jquery 制作一个推荐旋转器,但 Ajax 函数运行得太早,因此您会看到 HTML 更改,然后它淡出,然后又重新出现。我试图找出问题所在,但我不能似乎没有找到它。
<div class="testimonials">
<div id="testimonial"></div>
</div>
<script type="text/javascript">
function loadTestimonial(){
$("#testimonial").fadeOut(1000);
$.ajax({
url: "r/get_testimonial.php",
cache: false,
async: false,
timeout: 1000,
success: function(html){
$("#testimonial").html(html);
},
});
setTimeout($("#testimonial").fadeIn(1000), 2000);
}
$(document).ready(function(){
loadTestimonial();
setInterval (loadTestimonial, 5000)
});
</script>
I am making a Testimonial rotator with Jquery for my website, but the Ajax function runs too early, so you see the HTML change, then it fades out, and back in. I've tried to figure out the problem, but I can't seem to find it.
<div class="testimonials">
<div id="testimonial"></div>
</div>
<script type="text/javascript">
function loadTestimonial(){
$("#testimonial").fadeOut(1000);
$.ajax({
url: "r/get_testimonial.php",
cache: false,
async: false,
timeout: 1000,
success: function(html){
$("#testimonial").html(html);
},
});
setTimeout($("#testimonial").fadeIn(1000), 2000);
}
$(document).ready(function(){
loadTestimonial();
setInterval (loadTestimonial, 5000)
});
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个代码:
你的代码出了什么问题? ajax 代码被调用 imidiatly ,它将在准备好后替换旧的 HTML,我上面所做的是等待
fadeOut()
的回调,然后触发 Ajax 函数。这将获取源代码并淡入新的 HTML。您可能认为它是一个同步函数(因为 Ajax 有
async: false
),但 jQueryfadeOut
也是异步的,所以您不能像您那样等待。Try this code:
What went wrong with your code? The ajax code was called imidiatly which will replace the old HTML when it is ready, what I do above is wait for the callback of the
fadeOut()
and then trigger the Ajax function. Which will get the source andfadeIn
the new HTML.You might think it's an sync function (because the Ajax had
async: false
), but the jQueryfadeOut
is also async, so you can not wait for that the way you did.