I am using the themoviedb.org API which provides JSONP API that returns data for films etc.
Am trying to create a form that you can search a film and it will return 5 most relevant movie titles based on the query.
Currently I am using:
success: function(parsed_json) {
console.log(parsed_json);
$(".search").append("<li data-id=" +parsed_json["results"]["0"]["id"]+ ">" + parsed_json["results"]["0"]["original_title"] + "</li>");
$(".search").append("<li data-id=" +parsed_json["results"]["1"]["id"]+ ">" + parsed_json["results"]["1"]["original_title"] + "</li>");
$(".search").append("<li data-id=" +parsed_json["results"]["2"]["id"]+ ">" + parsed_json["results"]["2"]["original_title"] + "</li>");
$(".search").append("<li data-id=" +parsed_json["results"]["3"]["id"]+ ">" + parsed_json["results"]["3"]["original_title"] + "</li>");
$(".search").append("<li data-id=" +parsed_json["results"]["4"]["id"]+ ">" + parsed_json["results"]["4"]["original_title"] + "</li>");
$(".search").append("<li data-id=" +parsed_json["results"]["5"]["id"]+ ">" + parsed_json["results"]["5"]["original_title"] + "</li>");
}
to append all movie titles with data-id = the movie id. This seems to be ALOT of coding and I was wondering whether there is a way I could use each() to append the first 5 relevant movie titles.
Info on the JSONP API: http://help.themoviedb.org/kb/api/jsonp
Working JSFiddle: http://jsfiddle.net/javascript/5ApuF/
EDIT:
I have tried:
success: function(parsed_json) {
var textToInsert = [];
var i = 0;
var length = parsed_json.length;
for (var a = 0; a <length; a += 1) {
textToInsert[i++] = '<li>';
textToInsert[i++] = parsed_json[a];
textToInsert[i++] = '</li>' ;
}
$('.search').append(textToInsert.join(''));
}
I believe something like this should work just fine for your needs…
Goodluck! I edited this because I forgot you wanted only 5 results 🙂
–al