2014-12-03 4 views
0

jQuery와 AJAX를 사용하여 매 초마다 반복하여 콘솔을 새로 고치는 스크립트를 만들었습니다.반복 루핑 AJAX 쿼리

페이지는과 같이 설정입니다 : index.php 메인 페이지가 여러 AJAX 스크립트를 실행하고 반환 된 내용으로 index.php의 몸을 대체 할 수있는 버튼입니다 index.php -> console.php -> consoleQuery.php

. console.php이고 부분이 console.php 인 스크립트 중 하나는 다음 스크립트를 포함합니다.

window.setInterval(function() { 
    $.ajax({ 
     type: "POST", 
     url: "ajax/consoleQuery.php", 
     data: "", 
     success: function(response) { 
      $("#consoleBody").html(response); 
     } 
    }); 
    console.log("Console refreshed"); 
}, 1000); 

이 스크립트는 consoleQuery.php을 호출하여 기본적으로 페이지 본문을 업데이트하고 매 초마다 새로 고칩니다.

problme (예 index.php -> home.php 용) index.php
페어런트 다른 페이지 그게 home.phpindex.php 본체와 교체 루프를 일으키는 JS 여전히 백그라운드에서 발생하는 클릭에 따라, 그러나이다. 또한 console.php을 다시 트리거하면 초당 두 번씩 콘솔을 새로 고치고 여러 번 클릭하면 계속 켜집니다. 본질적으로 루프는 여러 인스턴스에서 실행됩니다.

내가 시도하고 싶은 것은 console.php을 요청하지 않는 AJAX 요청 중 하나를 트리거 할 때 페이지 몸체를 새로 고치는 루핑 스크립트를 중단하십시오.

다른 페이지에 액세스 할 때 루프를 중지 할 수있는 방법이 있습니까? 미리 감사드립니다!

답변

2

당신이 타이머 ID를 잡아 경우 : 당신은 아마 모든 서브 페이지의 AJAX 요청에 그것을 취소 할

clearInterval(consoleRefreshTimer); 

을하고 렌더링 일단 시작 :

var consoleRefreshTimer = window.setInterval... 

는 당신은 그것을 중지 할 수 있습니다 그것을 필요로하는 서브 페이지. 심지어 서브 페이지가 setupteardown 함수를 정의하고 표시 한 직후 setup으로 전화를 걸려면 새 AJAX 요청을 시작하기 바로 전에 teardown으로 전화하십시오. 또는 기본 페이지에서이 기능을 래핑 할 각 페이지에 대한 개체를 만듭니다. 빠르고 불쾌한 예 :

var subpages = { 
    main: { 
    url: "http://example.com/main", 
    }, 
    console: { 
    url: "http://example.com/console", 
    setup: function() { 
     this.timer = setInterval(function() { console.log("consoled!"); }, 1000); 
    }, 
    teardown: function() { 
     clearInterval(this.timer); 
    } 
    } 
}; 

var getSubpage = (function() { 
    var currentSubpage = {}; 
    return function(key) { 
    var subpage = subpages[key]; 
    if (currentSubpage.teardown) currentSubpage.teardown(); 
    console.log("loading " + key + " (actually faking it with timers)"); 
    setTimeout(function() { 
     currentSubpage = subpage; 
     console.log("showing " + key); 
     if (currentSubpage.setup) currentSubpage.setup(); 
    }, 500); 
    }; 
})(); 

getSubpage('main'); // main is loaded 
getSubpage('console'); // console is loaded; console timer starts up 
getSubpage('main'); // main is loaded; console timer stops 
+0

정확히 내가 필요한 것! console.php AJAX 스크립트 내에서'setInterval' 함수가 호출 되었기 때문에 setup 및 teardown 메소드가 작동하지 않았습니다. 그러나 변수를 생성하고 간격을 지우는 방법을 사용하면 완벽하게 작동했습니다! 도와 주셔서 대단히 감사합니다! – SteppingHat