最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing data sent by sendBeacon - Stack Overflow

programmeradmin3浏览0评论

Documentation indicates sendBeacon sends its data via a HTTP POST request, but in PHP the $_POST variable seems to be an empty array.

Here is my javascript code : navigator.sendBeacon('beacon_log.php','My lost data')

What am I doing wrong?

Update :

Found that if I use navigator.sendBeacon('beacon_log.php?g_data=My data ok','Still lost!') I can access the gdata with $_GET Why would that be when the $_SERVER['REQUEST_METHOD']=POST ?

Documentation indicates sendBeacon sends its data via a HTTP POST request, but in PHP the $_POST variable seems to be an empty array.

Here is my javascript code : navigator.sendBeacon('beacon_log.php','My lost data')

What am I doing wrong?

Update :

Found that if I use navigator.sendBeacon('beacon_log.php?g_data=My data ok','Still lost!') I can access the gdata with $_GET Why would that be when the $_SERVER['REQUEST_METHOD']=POST ?

Share Improve this question edited Oct 12, 2015 at 4:54 Mahks asked Oct 11, 2015 at 5:51 MahksMahks 6,7796 gold badges31 silver badges32 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

here is how I get to do it:

Front-end: in my .js file:

window.onbeforeunload = () => {
  navigator.sendBeacon('php/record-stats.php', JSON.stringify(stats));
}

Back-end: in my PHP file

$request = file_get_contents('php://input');
$data = json_decode($request);

It was a lot of trial/errors to find it, I couldn't find any doc at the time...

In order to get print_r($_POST,1); in PHP the data has to be formatted for an HTTP POST request:

window.onpagehide = function(event)
{
 var fd = new FormData(); 
 fd.append('ajax', 'beacon'); 
 fd.append('name', 'John'); 
 navigator.sendBeacon(path+'/beacon/', fd);
}

This will yield the desired results for print_r($_POST,1); in PHP.

Additionally...

  • Don't use Beacon with onbeforeunload.
  • Don't use Beacon with onvisibilitychange because of WebKit/Safari.

The data from navigator.sendBeacon is found in $HTTP_RAW_POST_DATA

发布评论

评论列表(0)

  1. 暂无评论