programing

AJAX 요청을 정기적으로 실행하는 방법

golfzon 2023. 4. 4. 22:40
반응형

AJAX 요청을 정기적으로 실행하는 방법

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

이 스크립트는 5초마다 페이지를 새로고침 또는 새로 고칩니다.하지만 저는 jQuery와 AJAX 콜을 사용하고 싶습니다.가능합니까?

다른 사람들이 지적한 것처럼interval과 set Timeout이 이 기능을 수행합니다.폴 아이리쉬의 이 훌륭한 비디오에서 배운 좀 더 고도의 기술을 강조하고 싶다.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 메서드 또는setInterval()메서드를 사용하여 실행할 코드를 호출합니다.set Timeout을 사용하면 다음과 같이 할 수 있습니다.

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

반응형