具有 204 响应和回调功能的信标跟踪图像



我已经尝试了几天了,现在转换我的跟踪像素JS功能使用204 "no_content"响应。

我可以很容易地得到这个工作,但我需要能够触发一个回调函数之后。

当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);
        }
    }

跟踪被正确记录,但没有警报或控制台日志消息。这可能吗,还是我只是在浪费时间?

编辑,

基于下面的解决方案,这里是最终版本(这假设两个错误&Success将使用相同的回调。

    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);
        }
    }

您没有为image附加任何回调。您的测试if (beacon.onerror)结果为假,因为beacon.onerrornull

您应该使用if( "onerror" in beacon )来测试beacon是否具有onerror属性。

但是为什么不直接使用jquery的方法on呢?

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

最新更新