0

トラッキング ピクセル 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);
        }
    }
4

1 に答える 1

1

コールバックを画像に添付していません。isであるため、テストif (beacon.onerror)結果は false になります。beacon.onerrornull

if( "onerror" in beacon )プロパティがあるかどうかをテストするために使用する必要beaconがありonerrorます。

しかし、jquery のメソッドを使用しないのはなぜonですか?

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

$(beacon).on("done", function() {
    alert("Jquery done");
});
于 2016-08-12T07:16:11.570 に答える