javascript - navigator.sendBeacon with applicationx-www-form-urlencoded - Stack Overflow

I'm trying to send a POST request on the beforeunload event using navigator.sendBeacon, but the da

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?

Share Improve this question asked Aug 23, 2017 at 18:46 user2039981user2039981
Add a ment  | 

2 Answers 2

Reset to default 7

Content-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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信