【问题标题】:Why is this $.ajax function successful only the second time it's called?为什么此 $.ajax 函数仅在第二次调用时才成功?
【发布时间】:2014-09-25 03:52:50
【问题描述】:

我正在尝试使用烂番茄 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);
                } 
            });
        }
    });
});

【问题讨论】:

  • 作为旁注(function($){ ... 不是 DOM 就绪处理程序

标签: javascript jquery ajax json rotten-tomatoes


【解决方案1】:

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

【讨论】:

  • 我将 reviewApiRequest 的声明下移到了成功函数中,它起作用了。感谢您的提示!
猜你喜欢
  • 2021-06-09
  • 1970-01-01
  • 2019-03-07
  • 2013-04-08
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多