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
?
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
?
2 Answers
Reset to default 7Content-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);
Read php://input
and run it through parse_str()
. Basically:
$MY_POST = null;
parse_str(file_get_contents('php://input'), $MY_POST);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744142083a4560250.html
评论列表(0条)