admin管理员组

文章数量:1316841

I'm sorry in advance, my native language is not English :(

Since in Chrome version 80 the AJAX queries no longer work in the unload event, I require another alternative, I read about Navigator.sendBeacon the problem is that I did not find an example to send multiple data, for example in AJAX have this:

$(window).on('unload', function() {
    console.log('ajax unload');
    $.ajax({
        type: 'POST',
        url: 'config/myphpfile.php',
        async: false,
        data: {
            xvar1: var1,
            xvar2: var2,
            xvar3: 0
        },
        success: function(data) {
            console.log('work!');
        }
    });

As you can see in this AJAX event, it sent 3 variables to my PHP, and one of them the var2 is an array, how can I pass multiple variables in the same way with the Navigator.sendBeacon function, have you done something similar?

I'm sorry in advance, my native language is not English :(

Since in Chrome version 80 the AJAX queries no longer work in the unload event, I require another alternative, I read about Navigator.sendBeacon the problem is that I did not find an example to send multiple data, for example in AJAX have this:

$(window).on('unload', function() {
    console.log('ajax unload');
    $.ajax({
        type: 'POST',
        url: 'config/myphpfile.php',
        async: false,
        data: {
            xvar1: var1,
            xvar2: var2,
            xvar3: 0
        },
        success: function(data) {
            console.log('work!');
        }
    });

As you can see in this AJAX event, it sent 3 variables to my PHP, and one of them the var2 is an array, how can I pass multiple variables in the same way with the Navigator.sendBeacon function, have you done something similar?

Share Improve this question asked Feb 6, 2020 at 22:14 Israel Correa QuevedoIsrael Correa Quevedo 531 silver badge6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You could use the FormData Object

// URL to send the data to
let url = '/api/my-endpoint';

// Create a new FormData and add a key/value pair
let data = new FormData();

// Append data to FormData object
data.append('xvar1', var1);
data.append('xvar2', var2);
data.append('xvar3', 0);

let result = navigator.sendBeacon(url, data);

if (result) { 
    console.log('Success!');
} else {
    console.log('Failure.');
}

I based this solution from: https://www.smashingmagazine./2018/07/logging-activity-web-beacon-api/#using-navigator-sendbeacon

Read more about the FormData Object here: https://developer.mozilla/en-US/docs/Web/API/FormData

本文标签: javascriptAJAX replacement with sendBeaconStack Overflow