2016-02-24 1 views
0

Я рассмотрел другие вопросы, связанные с этим, и кажется, что мне нужно дождаться завершения первого запроса Ajax, прежде чем продолжить со следующего. Я думал, что код ниже будет делать это, но по какой-то причине запрос срабатывает дважды.Ajax срабатывает дважды, заменяя последнее содержимое запросов - Rails 4

function infiniteScroll() { 
    if($('#infinite-scrolling').size() > 0) { 
    $(window).on('scroll', function(){ 
     //Bail out right away if we're busy loading the next chunk 
     if(window.pagination_loading){ 
     return; 
     } 
     var more_url = $('.pagination a.next_page').attr('href'); 
     if(more_url && $(window).scrollTop() > $(document).height() - $(window).height() - 50){ 
      //Make a note that we're busy loading the next chunk. 
      window.pagination_loading = true; 
      $('.pagination').html('<img src="/assets/ajax_loader.gif" alt="Loading..." title="Loading..." />') 
      $.getScript(more_url).always(function(){ 
      window.pagination_loading = false; 
     }); 
     } 
    }); 
    } 
} 

файл js.erb

$('#all_images').append("<%= j render 'shared/image_ajax' %>"); 
console.log('script fired'); 
<% if @images.next_page %> 
    $('.pagination').replaceWith('<%= j will_paginate @images %>'); 
<% else %> 
    $(window).off('scroll'); 
    $('.pagination').empty(); 
<% end %> 

Так что, когда я прокрутить страницу вниз (очень медленно как хорошо только, чтобы захватить событие) я получаю это в моей консоли

XHR finished loading: GET "http://localhost:3000/portfolio?page=2&_=1456333727211" 
script fired 
XHR finished loading: GET "http://localhost:3000/portfolio?_=1456333727212&page=3" 
script fired 

Am I не справляетесь с этим правильно или можете ли кто-нибудь увидеть какие-либо потенциальные проблемы здесь?

Любая помощь приветствуется

Спасибо

Update

Это пример разметки, который генерируется при создании первого свитка

Итак, когда страница нагружает 4 Результаты показаны

<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest" id="image_18" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest" id="image_17" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 Landscapes" id="image_16" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 Landscapes" id="image_15" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 

Затем я прокручиваю и еще 4 результатов получить добавляется

<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest" id="image_18" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest" id="image_17" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 Landscapes" id="image_16" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 Landscapes" id="image_15" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest" id="image_14" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest" id="image_13" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest Landscapes" id="image_12" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 
<div class="image isotope-item ok-md-3 ok-xsd-12 ok-sd-6 PlacesOfInterest Landscapes" id="image_11" style="position: absolute; left: 24.9593%; top: 0px;">...</div> 

Однако как пользователь я вижу только 4 изображения (4 просто добавляется заменить первые четыре загружен), после этого, хотя событие прокрутки работает, как ожидалось

ответ

0

Вы можете проверить, если $.active возвращает 0; если это так, первый запрос ajax был завершен.

Так что в вашем случае:

if ($.active !== 0) { 
    return; 
} 

В качестве альтернативы, вы можете также попробовать $.ajaxStop()

Подробнее здесь: http://api.jquery.com/ajaxStop/

+0

Спасибо за ваш ответ, но я боюсь, что не помогает , Я добавил пример разметки, которая создается при первом прокрутке – Richlewis

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