如何解决JSON字符串化将完整的数组元素转换为PHP中数组的键
我正在尝试将sendBeacon
方法附加到Web应用程序中的页面之一。我尝试使用简单的request
方法并通过AJAX
方法发送sendBeacon()
。两者都给出不同的结果,没有一个可用。请提出建议。
html.php
<body>
<button onclick="setzero();">
click me
</button>
<script>
function setzero(){
var settings = {
"url":"ttstt.php","method":"POST","data": JSON.stringify({"val":0})
};
$.ajax(settings).done(function(e){console.log(e);});
}
window.addEventListener("unload",function() {
navigator.sendBeacon("ttstt.php",JSON.stringify({"val":1}));
});
</script>
</body>
ttstt.php
$val = ($_POST);
print_r($val);
当我点击html.php
上的按钮时,得到以下结果。
!!请注意,完整的数组位于关键部分。 !!
Array
(
[{"val":0}] =>
)
重新加载页面以启动sendBeacon()
时,结果是[]
。
解决方法
我刚刚在PHP代码中更改了以下内容
$val = file_get_contents("php://input");
$json = json_decode($val);
echo $json['val']; //This gives output as 0,which I was looking for.
同样的代码也可用于sendBeacon()数据。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。