2015-02-21 4 views
1

у меня есть JSon объект> 15k фильмов, содержащих IMDb идентификаторы, как этотвыборки данных фильмов из API, в JavaScript

0: ObjectID: "1." 
    IdIMDb: "tt2322441" 
    Title: "Fifty Shades of Grey" 
    Year: 2015 
1: ObjectID: "2." 
    IdIMDb: "tt1617661" 
    (...) 

И я ищу, чтобы закончить эти данные с данными из других API,

Мой вопрос: что является наиболее эффективным способом, чтобы завершить свои данные с да ta из этого api?
Я планирую запустить эту программу только один раз и сохранить результат, чтобы он мог соблюдать ограничения api.

Моя первая идея состояла в том, чтобы сделать что-то вроде этого

data.forEach(function (d, i) { 
    d.Poster = OMDbApi(d.IdIMDb); 
    ... 
} 

function OMDbApi(i) { 
    $.ajax({ 
     url:"http://www.omdbapi.com/?i="+i+"&plot=short&r=json", 
     crossDomain: true, 
     dataType: "jsonp", 
     success: function (response) { 
      return response.Poster; 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      error = 1; 
     } 
    }); 
} 

Спасибо за любую помощь вы можете предоставить :-)

+0

Ваша текущая настройка не будет работать из-за асинхронного использования AJAX. – Mouser

+0

@ Показанная ссылка на Mouser включена в CORS, поэтому для нее не требуется jsonp – charlietfl

+0

@charlietfl, тогда не обращайте внимания на вторую часть. – Mouser

ответ

2
var totalCalls = 15000; 
    var calls = 0; 
    data.forEach(function (d, i) { 
    OMDbApi(I, d.IdIMDb); //posterCall 
} 

function OMDbApi(index, id) { 
    $.ajax({ 
     url:"http://www.omdbapi.com/?i="+id+"&plot=short&r=json", 
     crossDomain: true, 
     dataType: "jsonp", 
        dataObj : index, 
     success: function (response) { 
      window.data[this.dataObj].Poster = response.poster; 
          calls++; 
          if (calls == totalCalls) 
          { 
           alert("We're done"); 
          } 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      error = 1; 
     } 
    }); 
} 

Эта работа с асинхронной природы Ajax.

You might want to keep track of all the requests you make and show a message when all the requests are finished. I've added a simple example of how to keep track. The essence is that you know how many calls you're going to make. So you need to count the amount of ids and multiply that amount by the calls needed to complete the date. For example: every object has to make three calls to complete the data; poster, director and runtime. There are 14500 objects. This will result in a total of 3*14500 = 43500 calls. The script add 1 to the variable calls when a call is completed. When the calls equals the totalCalls an alert is shown.

+0

Я получаю ошибки: «Неотдача ReferenceError: respone не определена» в строке «iObject.Poster = respone.poster;» –

+0

@ user456789123 Тогда исправьте мою опечатку ;-) – Mouser

+0

ouch Я не заметил этого :-) –

Смежные вопросы