我正在尝试发送 POST
请求 beforeunload
事件使用 navigator.sendBeacon
,但数据没有到达 PHP $_POST
.我认为这是因为在使用 navigator.sendBeacon
时标题 Content-Type
始终设置为 text/plain;charset=UTF-8
,但在我的情况下,因为我需要发送一个查询字符串,因此使用 application/x-www-form-urlencoded
.
var amountOfApples = 0;
...
addEventListener("beforeunload", function(e) {
navigator.sendBeacon("save.php", "key=apples&value=" + amountOfApples);
});
我怎样才能做到这一点并确保标题设置为
application/x-www-form-urlencoded
?
最佳答案
Content-Type
Beacon API 使用的 header ,取决于您传递给 sendBeacon
的实例类型第二个参数。
应用程序/x-www-form-urlencoded
发送application/x-www-form-urlencoded
, 使用 UrlSearchParams
实例。
var params = new URLSearchParams({
key : 'apples',
values : amountOfApples
});
navigator.sendBeacon(anUrl, params);
多部分/表单数据
发送
multipart/form-data
header ,使用 FormData
实例。var params = new FormData();
params.append('key', 'apples');
params.append('value', amountOfApples);
navigator.sendBeacon(anUrl, params);
应用程序/json
发送
application/json
header ,使用 Blob
并设置其类型。var data = {
key : 'apples',
values : amountOfApples
};
var params = new Blob(
[JSON.stringify(data)],
{type : 'application/json'}
);
navigator.sendBeacon(anUrl, params);
关于javascript - navigator.sendBeacon 与 application/x-www-form-urlencoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45847276/