0

我一直在嘗試幾天,將我的跟蹤像素JS功能轉換爲使用204「no_content」響應。帶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

你AREN」牛逼附加任何回調到圖像。您的測試結果if (beacon.onerror)在假的,因爲beacon.onerrornull

您應該使用if("onerror" in beacon)來測試是否beacononerror財產。

但是,爲什麼不只是使用jQuery的方法on

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

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

哇,本來可以發誓我以前試過.on('錯誤')。現在工作得很好。衛生署! –

+0

會改變它,如果(!beacon.onerror)工作類似於if(在信標中的「onerror」)? –

+0

要確認其他人,!beacon.onerror也可以正常工作。感謝@Busky提供快速解決方案。 –