Mar*_* N. 4 html javascript api ajax
我目前正在参与一个学校项目,其中使用 Spotify API。现在我已经收到了某人正在听的当前歌曲。
但问题是,只有在刷新或打开站点后才会收到信息,但我希望它每秒保持刷新(而不刷新整个页面),以便与侦听器保持最新状态。这里有人知道我如何实现这一目标吗?
这是我正在使用的AJAX请求(我不确定它是否有用或什么)
$.ajax({
url: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
userInfoPlaceholder.innerHTML = userInfoTemplate(response);
console.log(response);
$('#login').hide();
$('#loggedin').show();
}
});
Run Code Online (Sandbox Code Playgroud)
如果我需要发布任何其他代码才能提供帮助,请告诉我!
您可以通过使用 setTimeout 或 setInterval 来实现此目的。
不同之处在于 setInterval以指定的时间间隔一次又一次地执行给定的函数(直到调用 clearInterval() 函数);setTimeout在指定的时间间隔后执行给定的函数一次。
在您完成必要的流程并做出回应后。您可以在函数末尾递归调用 makerequest() 函数。该行包含注释,提供 10 秒后再次调用的 makerequest() 函数。
function makerequest() {
$.ajax({
url: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
userInfoPlaceholder.innerHTML = userInfoTemplate(response);
console.log(response);
$('#login').hide();
$('#loggedin').show();
//process with the response and other stuffs
setTimeout(makerequest, 10000); //recursive call
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4334 次 |
| 最近记录: |