Search code examples
httpgetangularjsitunes

AngularJs and itunes


I'm just trying to do a basic call on the itunes search api using angularjs http.

$http.jsonp("http://itunes.apple.com/search", {params:{"term":"jack+johnson"}})
                .success(function (data, status, headers, config) {
                    console.log("is scope : " + data);
                }).error(function (data, status, headers, config) {
                    console.log("error" + status);
                });

The requests is well done (status:200) and I can see that the json is retrieved, this is an extract :

{
 "resultCount":50,
 "results": [
{"wrapperType":"track", "kind":"song", "artistId":909253, "collectionId":120954021,                 "trackId":120954025, "artistName":"Jack Johnson", "collectionName":"Sing-a-Longs and Lullabies     for the Film Curious George", "trackName":"Upside Down", "collectionCensoredName":"Sing-a-    Longs and Lullabies for the Film Curious George", "trackCensoredName":"Upside Down",     "artistViewUrl":"https://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4",     "collectionViewUrl":"https://itunes.apple.com/us/album/upside-down/id120954021?    i=120954025&uo=4", "trackViewUrl":"https://itunes.apple.com/us/album/upside-down/id120954021?    i=120954025&uo=4",  ....

But I have a js error : "Uncaught SyntaxError: Unexpected token : " on the first line of the json result ("resultCount":50).

I try using the transformResponse but the error occurs before.

Thanks


Solution

  • You forgot to add the callback function (JSON_CALLBACK):

    app.controller('Ctrl', function($scope, $http) {
        $http.jsonp("http://itunes.apple.com/search", {
            params: {
                "callback": "JSON_CALLBACK",
                "term": "jack+johnson"
            }
        }).success(function(data, status, headers, config) {
            console.log("is scope : " + data);
        }).error(function(data, status, headers, config) {
            console.log("error" + data);
        });
    });​
    

    From the angularjs $http.jsonp documentation:

    url – {string} – Relative or absolute URL specifying the destination of the request. Should contain JSON_CALLBACK string.