1

我試圖使用自動完成獲取從JSON格式的rottentomatoes電影建議。 但下面的代碼不顯示任何建議。jQuery autocomplete與爛番茄api

<script> 
var apikey = "5xq9w7z2mp7a6cnchkfy52yd"; 
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0"; 

var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey; 
var query = "Rocky"; 

$(document).ready(function() { 
$("#sample").autocomplete({ 
source: function(request, response) { 
     $.ajax({ 
      url: moviesSearchUrl + '&q=' + encodeURI(query), 
      dataType: "jsonp", 
      success: function(data) { 
        var movies = data.movies; 
        response(function(movies) { 
           return { 
             label: movies.title, 
             value: movies.title 
             } 
        }));   
        } 
     }); 
     } 
}); 
}); 
</script> 

對於完整的頁面源:https://gist.github.com/2018447 我還需要包括在建議名單的動畫縮略圖。任何人都可以幫助我嗎?

+0

什麼是你的錯誤控制檯說? – Phil 2012-03-11 23:11:35

+0

b [0]未定義 file://home/aaa/jqueryexample/js/jquery-ui-1.8.18.custom.min.js – rnk 2012-03-11 23:23:38

+0

我已更新我的答案以包含海報縮略圖。這應該可以解決你的問題 – Phil 2012-03-11 23:38:51

回答

4

您有一個語法錯誤(額外的)),並且錯過了調用以迭代movies數組(通常使用$.map())。

這是它應該是什麼樣子(更新:包括海報縮略圖

$("#sample").autocomplete({ 
    source: function(request, response) { 
     $.ajax("http://api.rottentomatoes.com/api/public/v1.0/movies.json", { 
      data: { 
       apikey: apikey, 
       q: request.term 
      }, 
      dataType: "jsonp", 
      success: function(data) { 
       response($.map(data.movies, function(movie) { 
        return { 
         label: movie.title, 
         value: movie.title, 
         thumb: movie.posters.thumbnail 
        } 
       }));   
      } 
     }); 
    } 
}).data("autocomplete")._renderItem = function(ul, item) { 
    var img = $("<img>").attr("src", item.thumb); 
    var link = $("<a>").text(item.label).prepend(img); 
    return $("<li>") 
     .data("item.autocomplete", item) 
     .append(link) 
     .appendTo(ul); 
}; 
​ 

在這裏工作的例子 - http://jsfiddle.net/df7tp/6/

+0

耶!它正在工作。非常感謝:)順便說一句..我可以使用**。data(「autocomplete」)._ renderItem **在建議中包含縮略圖嗎?爲此,我是否需要在響應部分添加圖像鍵? – rnk 2012-03-11 23:44:21

+0

@rnk你有沒有看到我的更新? – Phil 2012-03-11 23:45:21

+0

謝謝@Phil它看起來很可愛! – rnk 2012-03-11 23:50:00