ここ Stackoverflow で非同期関数と値を返す方法に関する多くの質問を読みましたが、これらのヒントを自分のプロジェクトに適用することはできません。ですから、そのためにあなたの助けを求めます。
iTunes 検索 API を使用してストア内の曲を検索し、それらを「プレイリスト」に追加しています。プロジェクトは JQuery で開発されています。
基本的に、「iTunesSearch」と呼ばれる検索ボックスに曲の名前を書き込んでから、「検索」と呼ばれるボタンをクリックすると、iTunes ストアで曲を取得するためのコードが実行されます。私がやりたいのは、曲の名前を取得して配列に入れ、それをページの div に表示してから、他の曲を検索してプロセスを何度も繰り返すことです。最後に、検索したすべての曲を含む配列が必要です。
コードは次のとおりです。
$(document).ready(function() {
$('#search').click(function(){
var media = "music";
var limitOfSearchResults = 1;
var thing = document.getElementById('itunesSearch').value;
var whatosearch = $('#itunesSearch').attr('value');
$.getJSON("http://itunes.apple.com/search?term=" + thing
+ "&country=us&limit=" + limitOfSearchResults
+ "&media=" + media
+ "&callback=?",function(data) {
songname = data["results"][0].trackName;
resultPlaylist = createPlaylist(song);
alert(resultPlaylist); //is always 1, it doesn't add songs when I repeat search
});
function createPlaylist(song){
var playlist = new Array ();
playlist.push(song);
return playlist.length; //to test if the array stores the results
)};
});
HTML 本文スニペットは次のとおりです。
<input id="itunesSearch" type="text" placeholder="Search for a song..">
<div id="resultiTunes"></div>
<input id="search" type= "button" value="Find!">
コールバックの外で songname 変数を渡し、それを使用して曲の名前を配列などに格納するにはどうすればよいですか? コールバックが後で実行されることが問題であることを理解しました。コールバック内で関数を呼び出してみましたが、曲を配列にスタックしません (失敗したため、このコードを含めていません)。何か案は?
前もって感謝します。