文档表明 sendBeacon
通过 HTTP POST 请求
发送其数据,
但在 PHP 中,$_POST
变量似乎是一个空数组。
这是我的 JavaScript 代码:navigator.sendBeacon('beacon_log.php','我丢失的数据')
我做错了什么?
更新:
发现如果我使用
navigator.sendBeacon('beacon_log.php?g_data=我的数据没问题','还是丢失了!')
我可以使用 $_GET
访问 gdata 为什么会在 $_SERVER['REQUEST_METHOD']=POST
时出现这种情况?
最佳答案
这是我的做法:
前端:在我的 .js 文件中:
window.onbeforeunload = () => {
navigator.sendBeacon('php/record-stats.php', JSON.stringify(stats));
}
后端:在我的 PHP 文件中
$request = file_get_contents('php://input');
$data = json_decode($request);
经过多次尝试/错误才找到它,我当时找不到任何文档......
关于javascript - 访问sendBeacon发送的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062002/