douyan6871 2019-03-19 22:07
浏览 136
已采纳

Fetch不发送帖子数据[重复]

This question already has an answer here:

I'm having this problem, where for some reason I can't send data to another PHP script with POST over the fetch API.

I've already checked other solutions and cleaned up my code, but it still won't work.

Maybe I'm missing something.

Here's my code:

function request(where, num, last, query){
    for (var i = num; i > 0; i--) {
        fetch("global/modul.php", {
            method: "POST",
            body: JSON.stringify({
                last: last,
                query: query
            }),
            headers:{
                'Content-Type': 'application/json'
            }
        }).then(function (response) {
            return response.text();
        }).then(function (data) {
            let html = data.trim();
            document.getElementById(where).innerHTML += html.trim();
        }).catch(function (error) {
            console.log('Request failed', error);
        });

        last = document.getElementById(where).lastChild.id;
    }
}

    var_dump($_POST);

Prints:

array(0) { }

I've also tested the solutions shown in Parse Javascript fetch in PHP, but it didn't solve the problem. I still don't get the POST data in my php-script.

</div>
  • 写回答

1条回答 默认 最新

  • duanci9305 2019-03-19 22:24
    关注

    There is no problem with your JS code. However you need to look for the data in another variable in your PHP code, by reading php://input like so:

    $_POST = json_decode(file_get_contents('php://input'), true);
    

    Source: https://stackoverflow.com/a/39508364/2831645

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数