S
S
Svyatoslav Nemato2017-09-24 03:39:25
JavaScript
Svyatoslav Nemato, 2017-09-24 03:39:25

Ajax requests on scroll event?

var load = true;
$(document).ready(function(){
  $(document).on('click', '#test', function(e){
    $('#load').append('Идёт загрузка...');
    var page = $('#page').val();
    $.ajax({
      url: '/components/ajax/ajax.php',
      type: 'POST',
      data: JSON.stringify({ page: page }),
      contentType: 'application/json; charset=UTF-8',
      dataType: 'json'
    })
    .done(function(data) {
      if (data.error == 0) {
        $('#load_text_temp').html('');
        console.log(data.html);
        $('#page').val(parseInt(page) + 1);
      }
    });
    return false;
  });
  
  
  $(window).scroll(function(){
    if (!load) {
      return false;
    }
    if($(window).scrollTop() + $(window).height() >= $(document).height() - 200) {
      load = false;
      $('#load').append('Идёт загрузка...');
      var page = $('#page').val();
      $.ajax({
        url: '/components/ajax/ajax.php',
        type: 'POST',
        data: JSON.stringify({ page: page }),
        contentType: 'application/json; charset=UTF-8',
        dataType: 'json'
      })
      .done(function(data) {
        if (data.error == 0) {
          $('#load_text_temp').html('');
          console.log(data.html);
          load = true;
          $('#page').val(parseInt(page) + 1);
        }
      });
      return false;
    }
  });	
});


The problem is that when the "click" event is fired, the request runs in 168 ms
$(document).on('click', '#test', function(e){
Запрос
});


And when the "scroll" event is executed, the same request is executed in 5 seconds
$(window).scroll(function(){
Запрос
});

What's wrong with the code? How to correctly handle the scroll event?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question