javascript - 访问sendBeacon发送的数据

标签 javascript php

文档表明 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/

相关文章:

javascript - 轮播停止下拉菜单工作

javascript - 延迟 sweetalert2 中按钮的出现

php - 提交时进行 SVN 生产部署

javascript - DRY React : To extend or not. 我的团队似乎不同意

javascript - 我们如何或可以通过 npm 和 Meteor 使用 Node 模块?

javascript - 类型错误 : pos is undefined error

php - 将随机行从一个 MySQL 表复制到另一个具有不同模式的 MySQL 表

php artisan migrate [PDOException] 找不到驱动程序

php - Laravel Lighthouse - 按关系属性对查询进行排序

php - 使用多个 AJAX 操作的正确方法?