使用Ajax从IMDB API提取数据 [英] Using AJAX to Extract Data from IMDB API

查看:136
本文介绍了使用Ajax从IMDB API提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的code:的jsfiddle

HTML

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

jQuery的

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

}

$(礼)。每个(函数(){
      VAR文字= $(本)的.text();
      得到年(文字);
      $(本).append((+一年+));
});
 

解决方案

您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

这篇关于使用Ajax从IMDB API提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆