gpt4 book ai didi

javascript - 有没有更短的方法来刷新 div

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:33:34 24 4
gpt4 key购买 nike

我的页面中有一些元素,我需要每 5 秒刷新一次它们的内容。我将要向您展示的代码运行良好,但它看起来太长而且会 self 重复。当我只使用 setInterval 函数时,页面不会在间隔到来之前定期加载。你能建议一个更好的方法吗?提前致谢。这是我的代码:

var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
var refreshSongDetails=setInterval(function() {
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
}, 5000);

最佳答案

将您的 ajax 调用创建到一个函数中并调用它:

var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");

function ajaxCall() {
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
}

ajaxCall();

var refreshSongDetails = setInterval(ajaxCall, 5000);

关于javascript - 有没有更短的方法来刷新 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30195616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com