我的页面中有一些元素,我需要每5秒刷新一次内容.我要向你展示的代码运行良好,但看起来很长并重复自己.当我只使用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);
解决方法:
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);