2015-01-04 107 views
0

我正在使用Echo Nest API創建一個基本的Web應用程序,用於模板化和從API獲取數據。我只是想知道如何從JSON對象訪問「歌曲」中的'artist_name'&'title'對象並使用Handlebars.js將這些數據插入到我的模板中?當我按照我在下面寫的那樣做{{#each songs}}時,它不起作用。如何使用Handlebars.js訪問JSON對象?

提前致謝!

PS。珍妮崔西並不反映我的音樂品味。這只是我測試它時出現的JSON對象!

<main> 
    <section> 
    <input type="text" id="genre-name" placeholder="Enter the Genre Here." /> 
    <input type="number" id="bpm" placeholder="Enter the BPM here." id="bpm"> 
    <a href="#" id="fetch-albums">Fetch</a> 
    </section> 

    <section id="results"> 
    </section> 

</main> 

<template id="results-template"> 
    <article> 
    <header> 
     {{#each songs}} 
     <h1>{{ this.artist_name }}</h1> {{/each}} 
</template> 

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript" src="handlebars.js"></script> 
<script type="text/javascript"> 
    $('#fetch-albums').on('click', function() { 
    var genre = $('#genre-name').val(); 
    var bpm = $('#bpm').val(); 
    var source = $('#results-template').html(); 
    var template = Handlebars.compile(source); 
    $.get('http://developer.echonest.com/api/v4/song/search?api_key=[hidden]&style=' + genre + '&min_danceability=0.65&min_tempo=' + bpm + '&results=5', function(data) { 
     $('#results').append(template(data)); 
    }); 
    }); 
</script> 

JSON對象

{ 
    "response": { 
    "status": { 
     "version": "4.2", 
     "code": 0, 
     "message": "Success" 
    }, 
    "songs": [{ 
     "artist_id": "AR8COOH1187B990D7D", 
     "id": "SOGMVZZ1393A2A9142", 
     "artist_name": "Jeanie Tracy", 
     "title": "I'm Gonna Get You" 
    }, { 
     "artist_id": "AR8COOH1187B990D7D", 
     "id": "SOGMIVN14248BD9E88", 
     "artist_name": "Jeanie Tracy", 
     "title": "Feel Like Dancing [Joey Negro Dubbed Out]" 
    }, { 
     "artist_id": "AR8COOH1187B990D7D", 
     "id": "SOIMUFZ1315CD4CDEC", 
     "artist_name": "Jeanie Tracy", 
     "title": "Do You Believe In Wonder (Stone & Nick Late Nite Diner Mix)" 
    }, { 
     "artist_id": "AR8COOH1187B990D7D", 
     "id": "SOEQTUW1315CD4FAB2", 
     "artist_name": "Jeanie Tracy", 
     "title": "Intro" 
    }, { 
     "artist_id": "AR8COOH1187B990D7D", 
     "id": "SOENYBA12A6D4F46C0", 
     "artist_name": "Jeanie Tracy", 
     "title": "Rosabel's Disco Diva Mix" 
    }] 
    } 
} 

回答

1
  1. <article><header>沒有結束標記。儘管HTML規範可能允許一些標籤忽略關閉(如<td>,afaik),雖然有些瀏覽器足夠寬容,但我不知道Handlebars編譯器是否相同。您的songs仍在response之下。我認爲它應該是{{#each response.songs}}。另外,我認爲你也可以用{{ artist_name }}

+0

非常感謝! – fadfad