문제

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+")");
});
도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top