后台接收fetch传递的post数据

fetch官网post传递数据用的是JSON.stringify()的形式:

fetch('http://www.tingchunyu.com/test/fetch_test/fetch_getuser_test.php', {
    body: JSON.stringify({id:666}),
    headers: {
        'content-type': 'application/json'
    },
    method: 'POST',
})
    .then(response => {
        if (response.ok){//判断请求是否成功
            return response.json()
        }
        throw new Error('请求发生错误')
    })
    .then(data=>{
        console.log(data)
    })
    .catch(error => {
        console.log(error)
    })

但是像上面这样写后台按照以前接收变量的方式总是接收null。造成这个的原因是因为这样向服务器提交的数据是一个json数据,而不是传统的formdata。如下图所示:
fetch发起post请求时的数据格式
$.ajax()发起post请求时的数据格式
因此想让后台接收到数据有以下两种解决方法

  1. 将上面代码body的格式做以下修改
body: JSON.stringify({id:666})修改为 body: 'id=666'
//如果有多个参数可以用"&"进行连接 如:body: 'id=666&type=0'

但是这种写法如果有许多参数要传递的话就有点麻烦了。


  1. 第二种方法,保持以上代码不变。修改后台接收参数的方式。以PHP为例:
// 将 $_POST['id']修改成以下方式
$data = json_decode(file_get_contents('php://input'),true);
$id = $data['id'];//这样就可以接收到ID了

猜你喜欢

转载自blog.csdn.net/one_four_two/article/details/86660565