ajax + python 으로 데이터를 가져올때 일어나는 pending 현상 어떻게 해결해야 하나요?

조회수 3627회

python 과 ajax를 이용해서 데이터베이스에 있는 값을 체크해서 오는데요

값 체크는 자바스크립트 setInterval () 함수를 사용해서 일정시간이 되면 확인하도록 했습니다.

python에서 값을 가져오는건 ajax로 가져오고요..

그런데 python에서 값을 가져올때 시간이 걸리면 ajax에서 pending이 생겨서 오류가 납니다.

이부분을 어떻게 해결해야 할지 몰라서요 ..

질문 1) Python에서 setInterval()과 같은 역할을해서 html로 계속 푸시 해줄수 있는 방법이 있는지 궁금합니다.

2) ajax 에서 pending이 생길때 해결할수 있는 방법이 있는지 궁금합니다.

소소코드

       $(document).ready(function()
       {

         setInterval (rotateImage, 80000);
         setInterval (changeCount, 1000);
       });


      function rotateImage(){

        var imgArr = $("#imgGroup_1").attr('src').split('/');
          imgNum = imgArr[3];
          imgNum = imgNum.replace('imgGroup_1_','');
          imgNum = parseInt(imgNum.replace('.jpg',''));
          if(imgNum == 9){
            imgNum = 1;
          }else{
            imgNum++;
          }


        Array.prototype.shuffle = function(){
        return this.concat().sort(
          function(){return Math.random() - Math.random();}
        );
        }

        var data = new Array();
        data[0] = '1';
        data[1] = '2';
        data[2] = '3';
        data[3] = '4';
        data[4] = '5';
        data[5] = '6';
        data[6] = '7';
        data[7] = '8';
        data[8] = '9';
        data[9] = '10';

        var arr = data.shuffle();

        for (var i = 0; i < arr.length; i++) {
          (function(index) {
              setTimeout(function() {
                var curSrc = $('#imgGroup_'+arr[index]).attr('src');
                $('#imgGroup_'+arr[index]).fadeOut(600, function(){
                  console.log("/static/img/imgGroup_"+arr[index]+"_"+imgNum+".jpg");
                  $(this).attr('src',"/static/img/imgGroup_"+arr[index]+"_"+imgNum+".jpg").bind('onreadystatechange load', function(){
                    if (this.complete) $(this).fadeIn(600);
                  });
                });
              }, i * 8000);
          })(i);
        }

      }


      function startCount(){


      }

      function changeCount(){

         $.ajax({
            url: '/_getCount',
            success: function(data){
                var increaseNum = data.result;
                var target_count = data.target_count;
                console.log(increaseNum);
                var countNum = parseInt($("#numOfcount").text().replace(',',''));

                if (target_count >= increaseNum){
                  new numberCounter(countNum,increaseNum);
                }
            }
          });


      }




         function numberCounter(countNum, newCountNum) {
             this.count = countNum;
             this.diff = 0;
             this.target_count = parseInt(newCountNum);
             this.target_frame = $("#numOfcount");
             this.timer = null;
             this.counter();
         };
             numberCounter.prototype.counter = function() {
                 var self = this;
                 this.diff = this.target_count - this.count;

                 if(this.diff > 0) {
                     self.count += Math.ceil(this.diff / 5);
                 }

                 this.target_frame.text(this.formatNumber(this.count));

                 if(this.count < this.target_count) {
                     this.timer = setTimeout(function() { self.counter(); }, 20);
                 } else {
                     clearTimeout(this.timer);
                 }
             };
             numberCounter.prototype.formatNumber = function(num) {
                 num+= '';
                 x = num.split('.');
                 x1 = x[0];
                 x2 = x.length > 1 ? '.' + x[1] : '';
                 var rgx = /(\d+)(\d{3})/;
                 while (rgx.test(x1)) {
                     x1 = x1.replace(rgx, '$1' + ',' + '$2');
                 }
                 return x1 + x2;
             };



      </script>
  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 1) Python에서 setInterval()과 같은 역할을해서 html로 계속 푸시 해줄수 있는 방법이 있는지 궁금합니다.

    socket 서버를 구현하면 가능합니다. (ex: 채팅 서버)


    2) ajax 에서 pending이 생길때 해결할수 있는 방법이 있는지 궁금합니다.

    
    function changeCount() {
      $.ajax({
        url: 'https://httpbin.org/get',
        success: function(data){
          console.log(data);
          setTimeout(changeCount, 5000);
        }
      });
    }
    
    changeCount();
    

    이런 형태로 setInterval 대신 ajax 리턴을 받은 후 setTimeout 으로 함수를 다시 호출하면
    ajax 리턴 전에 다시 요청하는 것을 방지 하면서 setInterval 을 사용하는 것과 같은 동작이 가능할 것 같네요.

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)