development

AJAX 요청을 정기적으로 실행하는 방법은 무엇입니까?

big-blog 2020. 8. 12. 22:16
반응형

AJAX 요청을 정기적으로 실행하는 방법은 무엇입니까?


<meta http-equiv="Refresh" Content="5">

이 스크립트는 5 초마다 페이지를 다시로드하거나 새로 고칩니다. 하지만 jQuery 및 AJAX 호출을 사용하여 수행하고 싶습니다. 가능할까요?


다른 사람들이 지적했듯이 setInterval 및 setTimeout이 트릭을 수행합니다. Paul Irish의 훌륭한 비디오에서 배운 좀 더 고급 기술을 강조하고 싶었습니다. http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

반복 간격보다 오래 걸릴 수있는주기적인 작업 (예 : 느린 연결의 HTTP 요청)에는를 사용하지 않는 것이 가장 좋습니다 setInterval(). 첫 번째 요청이 완료되지 않고 다른 요청을 시작하면 공유 리소스를 소비하고 서로 굶주리는 여러 요청이있는 상황이 될 수 있습니다. 마지막 요청이 완료 될 때까지 다음 요청을 예약 할 때까지 기다리면이 문제를 피할 수 있습니다.

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

간단하게 스케줄링에 성공 콜백을 사용했습니다. 이것의 단점은 하나의 실패한 요청이 업데이트를 중지한다는 것입니다. 이를 방지하려면 대신 전체 콜백을 사용할 수 있습니다.

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

예, JavaScript setTimeout()메서드 또는 setInterval()메서드를 사용하여 실행하려는 코드를 호출 할 수 있습니다. 다음은 setTimeout으로 수행 할 수있는 방법입니다.

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

당신은 사용할 수 있습니다 setTimeout또는 setInterval.

차이점은 setTimeout은 함수를 한 번만 트리거 한 다음 다시 설정해야한다는 것입니다. setInterval은 중지하라고 지시하지 않는 한 계속해서 표현식을 트리거합니다.


아래 코드를 시도했습니다.

    function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

지정된 간격 동안 예상대로 작동하지 않았고 페이지가 완전히로드되지 않았고 함수가 계속 호출되었습니다. 아래와 같이 별도의 함수로 setTimeout(executeQuery, 5000);외부 를 호출하는 것이 좋습니다 executeQuery().

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  updateCall();
}

function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}

$(document).ready(function() {
  executeQuery();
});

이것은 의도 한대로 정확하게 작동했습니다.

참고 URL : https://stackoverflow.com/questions/5052543/how-to-fire-ajax-request-periodically

반응형