0

我正在尝试使用烂番茄 API。在单击事件上,搜索会将最匹配的电影标题和缩略图图像的 JSON 数据返回到搜索输入。

完成第一个 $.ajax 请求后,使用 var resultID 发出第二个 $.ajax 请求,该请求在顶部声明并在第一个 $ajax 请求“成功”时设置。

截至目前,当我第一次单击时,它成功运行了第一个请求,但它无法运行 return json.total(在“完成”时),因为 resultID 被返回为“未定义”。但是我第二次点击,resultID 显然已经设置好了,因为它会成功返回 json.total。

我猜这是一个与我如何声明和调用 resultID(或 ajax 的异步触发)有关的简单问题,但我不确定它是什么。谁能解释一下?

var apiKey = '***********';
var resultID = "";

$('#search-submit').click(function(){
    var queryText = $('#movie-search').val();
    var queryURI = encodeURI(queryText);
    var searchApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=" + queryURI + "&page_limit=10&page=1&apikey=" + apiKey;
    var reviewApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies/" + resultID + "/reviews.json?review_type=top_critic&page_limit=10&page=1&country=us&apikey=" + apiKey;

    $.ajax({
        url: searchApiRequest,
        type: 'GET',
        dataType: 'jsonp',
        error: function() {
            console.log('there was error in processing the search request.');
        },
        success: function(json) {
            var movieInfo = json.movies[0];
            var noResultsMessage = 'your search returned no matches. Please try again.'; 
            var resultTitle = movieInfo.title;
            var resultThumb = movieInfo.posters.thumbnail;
            var resultDesc = movieInfo.critics_consensus;

            var reviewsPublicURL = movieInfo.links.reviews;
            var reviewsRequest = reviewsPublicURL;

            resultID = movieInfo.id; // supposed to set global var resultID to movieID

            $('.search-results').find('img').attr('src',resultThumb).end().find('h1').text(resultTitle).end().find('p').text(resultDesc);

        },
        complete: function() {
            $.ajax({
                url:reviewApiRequest,
                type: 'GET',
                dataType: 'jsonp',
                error: function(json) {
                    console.log('for whatever reason, we could not find any reviews of this movie');
                },
                success: function(json) {
                    console.log(json.total);
                } 
            });
        }
    });
});
4

1 回答 1

1

您不仅需要设置全局resultID,还需要刷新 a reviewApiRequest。当您更新时,它不会神奇地自行改变其值resultID

于 2014-01-16T17:51:57.190 回答