【问题标题】:navigator.sendBeacon with application/x-www-form-urlencodednavigator.sendBeacon 与 application/x-www-form-urlencoded
【发布时间】:2017-08-23 18:46:10
【问题描述】:

我正在尝试使用navigator.sendBeaconbeforeunload 事件上发送POST 请求,但数据没有到达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

【问题讨论】:

    标签: javascript ajax onbeforeunload


    【解决方案1】:

    Beacon API 使用的Content-Type 标头,取决于您传递给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 标头,请使用FormData 实例。

    var params = new FormData();
    params.append('key', 'apples');
    params.append('value', amountOfApples);
    navigator.sendBeacon(anUrl, params);
    

    应用程序/json

    要发送application/json 标头,请使用Blob 并设置其类型。

    var data = {
       key : 'apples',
       values : amountOfApples
    };
    
    var params = new Blob(
        [JSON.stringify(data)], 
        {type : 'application/json'}
    );
    navigator.sendBeacon(anUrl, params);
    

    【讨论】:

    • 由于Bug 747787,Chrome 将 URLSearchParams 作为 text/plain 而不是 application/x-www-form-urlencoded 发送,因此可能需要使用 Blob。 – 取自Kevin.
    【解决方案2】:

    阅读php://input 并通过parse_str() 运行它。基本上:

    $MY_POST = null;
    parse_str(file_get_contents('php://input'), $MY_POST);
    

    【讨论】:

    • "警告在 PHP 7.2 中使用这个没有结果参数的函数是非常不推荐和弃用的。"
    • 是的,对不起,我的错。更新了答案。
    • 我正要这么做!
    • 很好,你知道为什么 navigator.sendBeacon 不支持这个吗?
    • 据我所知,因为它并不是一个成熟的 XMLHttpRequest(或fetch() FWIW)替代品,但它只是为了获得一点点某处的数据。
    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2019-05-04
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多