fetch 上传json数据 PHP接收不到POST数据

JSON形式

let data = { "a" : 1 };
fetch('a.php', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: new Headers({
        'Content-Type': 'application/json'
    })
}).then(res => res.json())
    .catch(err => console.log(err))
    .then(res => console.log(res));

图片描述

表单形式

let formData = new FormData();
formData.append('b', '1');
fetch('a.php', {
    method: 'post',
    body: formData
}).then(res => res.json())
    .catch(err => console.log(err))
    .then(res => console.log(res));

图片描述

MDN文档fetch上传JSON

阅读 4.8k
3 个回答
index.js
let data = { "a" : 1 };
fetch('a.php', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(res => res.json())
    .catch(err => console.log(err))
    .then(resp => console.log(resp));
a.php
$post_input = file_get_contents('php://input');

图片描述

FormData 对象

会把 Content-Type 设置为 multipart/form-data

FORM POST

默认的 form[method=POST] 会将 Content-Type 设置为 application/x-www-form-urlencoded

这些都是预定义的,早期的标准会被保存到超全局变量 $_POST 下。

application/json

是较新的东西,不会被定义过去,但是PHP可以获取原始输入,在低版本的 PHP 中可以使用 $HTTP_RAW_POST_DATA 变量来获取原始内容,在新版本中被 file_get_contents('php://input') 所取代。

在 PHP 中,预定义的 $_POST 变量用于收集来自 method="post" 的表单中的值。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题