[英]How to receive Fetch() POST in php?
So i got this POST json method here , but can't understand how to get my json data所以我在这里得到了这个 POST json 方法,但不明白如何获取我的 json 数据
It's packed in BLOB which is packed in FormData它被包装在 BLOB 中,而 BLOB 被包装在 FormData 中
How to receive such POST in php?如何在 php 中接收此类 POST? (and convert this FormData(Blob) back to json?)
(并将此 FormData(Blob) 转换回 json?)
JS JS
const data = new FormData();
const jsonBlob = new Blob([JSON.stringify(myJSON)], {type: "application/json"});
data.append("data", jsonBlob);
fetch(website,{
method: "POST",
body: data,
}).then(resp=>{
if(!resp.ok){
const err = new Error("Error response");
err.resp = resp;
throw err;
}
console.log("OK");
}).catch(err =>{
console.error(err);
})
I'm big noobo, so i can't even receive it我是大菜鸟,所以我什至无法收到它
Seems like it works differently with fetch()
似乎它与
fetch()
的工作方式不同
PHP PHP
if(isset($_POST['data'])){
}
The simpliest way to send a JSON to server is to simply send it as the POST request body.将 JSON 发送到服务器的最简单方法是将其作为 POST 请求正文发送。 There is no need to wrap it like a file.
无需像文件一样包装它。 For example,
例如,
var myJSON = {
hello: 'world',
foo: 'bar',
};
fetch(website, {
method: "POST",
body: JSON.stringify(myJSON),
})
On server side, your message will be readable through the "php://input" stream .在服务器端,您的消息将通过“php://input” stream 读取。 You can read it like an ordinary file:
您可以像阅读普通文件一样阅读它:
$request_raw = file_get_contents('php://input');
$json_object = json_decode($request_raw);
You can save the below code as a PHP file and test it yourself.您可以将以下代码保存为 PHP 文件并自行测试。 On load, it would send itself another POST reqeust, parse it as key-value pairs, return it to your browser and show it:
加载时,它会向自己发送另一个 POST 请求,将其解析为键值对,将其返回到浏览器并显示:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$request_raw = file_get_contents('php://input');
$request = json_decode($request_raw);
foreach ($request as $key => $value) {
echo "{$key}: {$value}\n";
}
exit;
}
?>
<div id="result"></div>
<script>
var myJSON = {
hello: 'world',
foo: 'bar',
};
const data = new FormData();
fetch(document.location.href, {
method: "POST",
body: JSON.stringify(myJSON),
}).then(resp => {
if(!resp.ok){
const err = new Error("Error response");
err.resp = resp;
throw err;
}
console.log("OK");
return resp.text();
}).catch(err =>{
console.error(err);
}).then(body => {
document.getElementById('result').innerText = body;
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.