javascript - 请求后等待在 JQuery 中发送另一个请求

标签 javascript jquery ajax spotify

我正在使用 Spotify WEB API,其想法是当我单击下一首歌曲按钮时使用歌曲名称更新 html。

问题是,当我单击按钮时,它确实更新了歌曲,但更新到最后播放的一首,而不是当前的一首。

我尝试使用其他方式,例如“成功”和“完成”参数,但是当使用“完成”时它不会更新,而在“成功”时也会发生同样的情况。

我是否可以为下一个请求设置“等待”时间?

document.getElementById('skip-song').addEventListener('click', function(){
  $.ajax({
    type: 'POST',
    url:'https://api.spotify.com/v1/me/player/next',
    headers: {'Authorization': "Bearer " + access_token},
    }).done(function(data){
      $.ajax({
        url: 'https://api.spotify.com/v1/me/player/currently-playing',
        headers: {
          'Authorization': 'Bearer ' + access_token
        },
      }).done(function(response){
            currentPlayingPlaceholder.innerHTML = currentPlayingTemplate(response);
    });
  });
}, false);

最佳答案

通过引入超时,您可以在请求当前播放的歌曲之前等待几秒钟。我不知道你要等多久,感觉有点hacky。如果跳过功能返回当前正在播放的内容,那就太好了...

document.getElementById('previous-song').addEventListener('click', function() {
  $.ajax({
    type: 'POST',
    url: 'https://api.spotify.com/v1/me/player/previous',
    headers: {
      'Authorization': "Bearer " + access_token
    },
  }).done(function(data) {
    setTimeout(
      $.ajax({
        url: 'https://api.spotify.com/v1/me/player/currently-playing',
        headers: {
          'Authorization': 'Bearer ' + access_token
        },
      }).done(function(response) {
        currentPlayingPlaceholder.innerHTML = currentPlayingTemplate(response);
      }), 3000); //wait 3 seconds before updating the currently playing
  });
}, false);

关于javascript - 请求后等待在 JQuery 中发送另一个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45015447/

相关文章:

javascript - CKEditor 中的 keyup 事件

javascript - 如何让我的弹出图像继续显示?

jquery - jQuery v1.9.1 的 .attr() 复选框问题

jQuery 导致 "Synchronous XMLHttpRequest on the main thread is deprecated"警告

php - 有没有比 echo 更好的方法来做到这一点?

Javascript:表单验证导致选定的 Ajax Live Search 字段被重置为 Null?

javascript - 如何从 jquery datepicker 中获取选定的日期

Javascript:使用 FileSaver.js 将文本/blob 保存到文件中

javascript - 从外部 js 文件切换时,Firefox CSS3 转换不起作用

javascript - 如何初始化一次并一次又一次地将相同的值传递给另一个函数?