Using AJAX to Extract Data from IMDB API

2019-04-14 23:45发布

I'm trying to get the year of a film given its title using IMDB's API and then appending the year in parenthesis next to the title.

There's some fundamental JS or AJAX thing that I'm screwing up. Any help would be much appreciated!

This is my code: jsFiddle

HTML

<ol>
    <li>Jaws</li>
    <li>The Lord of the Rings</li>
</ol>

jQuery

function getYear(title)
{
    $.ajax({
      url: "http://www.imdbapi.com/?t=" + title,
        dataType: 'jsonp',
        success: function(data){
            var year = data.Year;
        }
    });

}

$("li").each(function() {
      var text = $(this).text();
      getYear(text);
      $(this).append(" ("+year+")");
});

1条回答
家丑人穷心不美
2楼-- · 2019-04-15 00:09

Your code is calling the AJAX function, but immediately going on to update the page before the asynchronous function returns. You need to include the code that updates the page in the callback to the AJAX function so that it executes when the data is ready.

I have reworked your code to this:

function getYear(title)
{
    $.ajax({
      url: "http://www.imdbapi.com/?t=" + $(title).text(),
        dataType: 'json',
        success: function(data){
            var year = data.Year;
            var text = $( this ).text();
            $(title).append(" ("+year+")");

        }
    });

}

$( "li" ).each(function() {

      getYear(this);
});

Which works successfully on this fiddle

查看更多
登录 后发表回答