0

204 "no_content"응답을 사용하기 위해 추적 픽셀 JS 기능을 변환하는 데 며칠 동안 노력했습니다.204 응답 및 콜백 기능이있는 비 이커 추적 이미지

이 작업을 쉽게 수행 할 수 있지만 나중에 콜백 함수를 실행할 수 있어야합니다.

204가 반환되면 다음과 같은 문제는 발생하지 않습니다.

beacon: function (opts) { 
     var beacon = new Image(); 

     opts = $.extend(true, {}, { 
      url: pum_vars.ajaxurl || null, 
      data: { 
       action: 'pum_analytics', 
       _cache: (+(new Date())) 
      }, 
      error: function() { 
       console.log('error'); 
      }, 
      success: function() { 
       console.log('success'); 
      } 
     }, opts); 

     // Create a beacon if a url is provided 
     if (opts.url) { 
      // Attach the event handlers to the image object 
      if (beacon.onerror) { 
       beacon.onerror = opts.error; 
      } 

      if (beacon.onload) { 
       beacon.onload = opts.success; 
      } 

      $(beacon).on('load', function(response, status, xhr){ 
       alert(status); 
      }); 

      // Attach the src for the script call 
      beacon.src = opts.url + '?' + $.param(opts.data); 
     } 
    } 

추적은 올바르게 기록되지만 경보 또는 콘솔 로그 메시지는 기록되지 않습니다. 이것이 가능합니까 아니면 그냥 시간 낭비입니까? 여기에 아래의 솔루션을 기반으로

편집 ------

는 최종 버전 (이 오류 & 성공 모두 같은 콜백을 사용하는 것으로 가정이다.

beacon: function (opts) { 
     var beacon = new Image(); 

     opts = $.extend(true, {}, { 
      url: pum_vars.ajaxurl || null, 
      data: { 
       action: 'pum_analytics', 
       _cache: (+(new Date())) 
      }, 
      callback: function() { 
       console.log('tracked'); 
      } 
     }, opts); 

     // Create a beacon if a url is provided 
     if (opts.url) { 
      // Attach the event handlers to the image object 
      $(beacon).on('error success done', opts.callback); 

      // Attach the src for the script call 
      beacon.src = opts.url + '?' + $.param(opts.data); 
     } 
    } 

답변

1

당신은 '때로 믿을 수 beacon.onerrornull 거짓 때문에의 이미지에 어떤 콜백을 부착 t. 귀하의 테스트 if (beacon.onerror) 결과.

당신은여부를 테스트에 if("onerror" in beacon)를 사용해야합니다은 onerror 속성을가집니다.

하지만 jquery의 메서드 on을 사용하지 않으시겠습니까?

$(beacon).on("error", function() { 
    alert("Jquery error"); 
}); 

$(beacon).on("done", function() { 
    alert("Jquery done"); 
}); 
+0

와우는 이전에 .on ('오류')을 시도했습니다. 이제 완벽하게 작동합니다. 도!. –

+0

if (! beacon.onerror)가 if ("onerror"in beacon)와 비슷하게 작동합니까? –

+0

다른 사람을 위해! beacon.onerror가 잘 작동하는지 확인하십시오. 빠른 솔루션을 제공하는 @Busky에게 감사드립니다. –