简体   繁体   中英

navigator.sendBeacon with application/x-www-form-urlencoded

I'm trying to send a POST request on the beforeunload event using navigator.sendBeacon , but the data doesn't get to the PHP $_POST . I think this is because when using navigator.sendBeacon the header Content-Type is always set to text/plain;charset=UTF-8 , but in my case since I need to send a query string and therefore use application/x-www-form-urlencoded .

var amountOfApples = 0;

...

addEventListener("beforeunload", function(e) {
    navigator.sendBeacon("save.php", "key=apples&value=" + amountOfApples);
});

How can I do this and make sure the header is set to application/x-www-form-urlencoded ?

Read php://input and run it through parse_str() . Basically:

$MY_POST = null;
parse_str(file_get_contents('php://input'), $MY_POST);

Content-Type header that Beacon API use, depend on type of instance you pass to sendBeacon second parameter.

application/x-www-form-urlencoded

To send application/x-www-form-urlencoded , use UrlSearchParams instance.

var params = new URLSearchParams({
   key : 'apples',
   values : amountOfApples
});
navigator.sendBeacon(anUrl, params);

multipart/form-data

To send multipart/form-data header, use FormData instance.

var params = new FormData();
params.append('key', 'apples');
params.append('value', amountOfApples);
navigator.sendBeacon(anUrl, params);

application/json

To send application/json header, use Blob and set its type.

var data = {
   key : 'apples',
   values : amountOfApples
};

var params = new Blob(
    [JSON.stringify(data)], 
    {type : 'application/json'}
);
navigator.sendBeacon(anUrl, params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM