【发布时间】:2019-08-09 02:49:11
【问题描述】:
我正在使用 spotify API 转储所有用户的播放列表以及包含的曲目名称。我想出了如何请求该信息,并试图将其存储在一个散列中,其中可以通过播放列表名称 (hash[playlistName] = [track1, track2, etc]) 找到一组曲目。当我 console.log 时,一切看起来都很好。
但是当我尝试使用句柄栏助手来遍历它并显示所有内容时,JavaScript 认为该对象是空的。这是一些代码:
//helper that will display eventually, but right now logs "undefined"
Handlebars.registerHelper('read_hash', function(hash){
console.log(hash.length); //undefined
console.log(Object.keys(hash); //undefined
console.log(hash); //looks fine.. results in screenshot..
});
//ajax request that successfully get's all of the playlist data I want
$.ajax({
url: 'https://api.spotify.com/v1/me/playlists',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
//make a new hash and put in template
var processed = 0;
response.items.forEach(function(e){
var playlistName = e.name;
//get tracks by nesting a request lol
$.ajax({
url: e.tracks.href,
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(responseTwo) { //returns track objects
playlists[playlistName] = responseTwo.items;
processed++;
}
}).done(function(){
if(processed >= response.items.length)
{
playlistPlaceholder.innerHTML = playlistTemplate({Playlists: playlists}); //get playlists
}
});
});
//handle bars template with call to read_hash
<script id="playlist-template" type="text/x-handlebars-template">
<h1>playlists</h1>
<table>
<tr>
<th>playlist</th>
<th>tracks</th>
</tr>
{{read_hash Playlists}}
</table>
</script>
另外,当我从 read_hash 控制台记录 JSON.stringify(hash) 时,我得到了我想要的结果......也许有些东西正在工作?
【问题讨论】:
-
read_hash在哪里调用? -
您正试图在对象被填充之前访问它,这从控制台显示
{ }的事实中可以看出。$.ajax是异步的。playlists[playlistName] = responseTwo.items;发生在playlistPlaceholder.innerHTML = playlistTemplate({Playlists: playlists});之后。还要注意小蓝色i框。 -
可能是控制台中延迟加载的经典案例,让人认为它已定义。
console.log(JSON.stringify(hash)); -
不管怎样,JavaScript 没有
hash类型,对象也没有实现为真正的哈希表。您可能需要登录typeof hash以查看您实际使用的内容。 -
看看Wait until all jQuery Ajax requests are done?。也可以用数组来完成。
标签: javascript jquery json ajax spotify