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

Beacon tracking image with 204 response & callback function

几天来我一直在尝试将我的跟踪像素 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);
        }
    }

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

编辑 ------

基于下面的解决方案,这里是最终版本(假设错误和成功都将使用相同的回调。

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

您没有为图像附加任何回调。您的测试 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");
});