fetch post PHP后台接收不到数据的问题

1.fetch()方法作用是跨网络异步获取资源,类似jQuery.ajax()方法,但是最近在使用fetch() post时,却怎么都接收不到,换了几种传参和接收的写法,怎么写都是接收到null,后来发现是php后台接收的问题,传参的写法是对的,正常的fetch()写法如下:

fetch('url', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body:JSON.stringify({
        id : "1024"
    })
}).then(function(res) {
    // 提取响应数据进行处理,json()方法可以将数据转换为json格式
    return res.json();
}).then(function(detail) {
    // 管道函数,接收上一个函数返回的内容
    console.log(detail);
}).catch(function(error) {
    // 网络出错或者禁止访问,404/500无法找到资源不会报错
    console.log(error);
});    

而php后台 $_POST 接收到null是因为上面这种正常写法向服务器提交的数据是一个json数据,而不是传统的formdata。

所以要修改下headers及body的格式:

headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
},
body : 'id=1024'

但是要传递多个参数时这种写法会很麻烦,且有的场景不支持(如传递一个数组),这时我们就要修改php后台的接收方式,不能再用 $_POST。

// 将$_POST['id']修改成以下方式
$data = json_decode(file_get_contents('php://input'),true);
// 这样就可以接收到ID了
$id = $data['id'];

2.GET请求方式,将参数直接加在url后即可

fetch('url?id=1024', {
    method: 'GET'
}).then(function(res) {
    // 提取响应数据进行处理,json()方法可以将数据转换为json格式
    return res.json();
}).then(function(detail) {
    // 管道函数,接收上一个函数返回的内容
    console.log(detail);
}).catch(function(error) {
    // 网络出错或者禁止访问,404/500无法找到资源不会报错
    console.log(error);
});    

 

你可能感兴趣的:(PHP,JavaScript)