使用Ajax从IMDB API提取数据数据、Ajax、IMDB、API

由网友(↘酒ιīe風暖﹏)分享简介:我试图让使用IMDB的API给它的标题一部电影的一年,然后追加旁边的标题括号中的一年。有说我把事情搞砸了一些基本的JS或AJAX的事情。任何帮助将是非常美联社preciated!这是我的code:的jsfiddle HTML < OL><李>大白鲨< /李><李>在环1...

我试图让使用IMDB的API给它的标题一部电影的一年,然后追加旁边的标题括号中的一年。

有说我把事情搞砸了一些基本的JS或AJAX的事情。任何帮助将是非常美联社preciated!

这是我的code:的jsfiddle

HTML

 < OL>
    <李>大白鲨< /李>
    <李>在环1所述的主; /李>
< / OL>
 

jQuery的

 功能得到年(冠军)
{
    $阿贾克斯({
      网址:http://www.imdbapi.com/?t=+称号,
        数据类型:JSONP,
        成功:功能(数据){
            VAR年= data.Year;
        }
    });

}

$(礼)。每个(函数(){
      VAR文字= $(本)的.text();
      得到年(文字);
      $(本).append((+一年+));
});
 
Ajax基本概念和作用 jQuery中 .get 方法 请求服务器Api接口获取 数据 Ajax代码执行过程分析 URL地址的组成 Api接口和接口文档

解决方案

您code被调用AJAX功能,但立即进行的同步的函数返回之前更新页面。您需要包括code,更新的页面回调到了AJAX功能,使其在数据准备好执行。

我已经重新设计你的code到这一点:

 功能得到年(冠军)
{
    $阿贾克斯({
      网址:http://www.imdbapi.com/?t=+ $(职称)的.text()
        数据类型:JSON,
        成功:功能(数据){
            VAR年= data.Year;
            VAR文字= $(本)的.text();
            $(标题).append((+一年+));

        }
    });

}

$(礼)。每个(函数(){

      得到年(本);
});
 

这在这个小提琴

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

阅读全文

相关推荐

最新文章