2016-12-10 2 views
0

Google custom search api говорит, чтобы использовать параметр num, чтобы указать количество результатов изображения, это только от 1 до 10. Я искал, как сортировать повтор поиска, чтобы получить более 10 изображений и I found this article. Он говорит:Как рассчитать текущую позицию индекса в запросе?

Даже если существует предел 8 фотографий мы можем получить от сервера в одном запросе, если мы изменим start parameter мы можем в конечном счете восстановить более 8 результатов.

Из документов, связанных над start означает индекс первого результата, чтобы вернуться.

Поэтому я применил то, что он использовал для запуска запроса, и я применил его к своему собственному коду, но теперь получаю 0 изображений.

var myCx = "MY_CX"; 
var myKey = "MY_KEY"; 
var lastQueriedName; 
var termS = "hello"; 

// This bit is from the link which runs against the currentSTARTposition 

var currentSearchPosition = 0; 
function calculateStartPosition(termS, shift) { 
if (lastQueriedName === termS) { 
    currentSearchPosition += shift; 
    if (currentSearchPosition < 0) { 
     currentSearchPosition = 0; 
    } 
    if (currentSearchPosition >= 100) { 
     currentSearchPosition = 92; 
    } 
} else { 
    lastQueriedName = termS; 
    currentSearchPosition = 0; 
} 
    return currentSearchPosition; 
} 

// This is my own code which works only if 
// I don't insert the above function and I remove start: position 

$.getJSON("https://www.googleapis.com/customsearch/v1", { 
     q: termS, 
     alt: "json", 
     searchType: "image", 
     cx: myCx, 
     start: currentSearchPosition, 
     num: 10, 
     key: myKey, 
     rights: "cc_publicdomain", 
     filter: "1", 
     imgType: "photo", 
     fileType: "jpg" 
    }, 
    function (data) { 
     $.each(data.items, function(i,item){  
      $(".my_images .row").append('<div class="col-sm-4"><div class="thumbnail"><img class="img-responsive" src="' + item.link + '"></div></div>'); 
     }); 
    }); 
}; 

ответ

0

В конце концов, это то, как я захватывая более 10 изображений, я повторить запрос и использовать параметр запуска: I сохранить начальное значение между вызовами

function createGoogleImagesLoader(initialValue) { 
     var _start = initialValue || 1; 
     var imagesCount = 10; 

     return function() { 
      $.getJSON("https://www.googleapis.com/customsearch/v1", { 
       ... 
       num: imagesCount, 
       start: _start 
      },..); 
      _start += imagesCount; 

     } 
    } 

var googleImages = createGoogleImagesLoader(); 
googleImages() // load from 0 to 10 
googleImages() // load from 10 to 20 etc.