duanchongzi9997 2019-04-22 03:33 采纳率: 0%
浏览 811
已采纳

为什么PHP无法从Js FormData获取$ _POST数据?

I want to send JSON data (in this case is client timestamp) to my server. However, my code seem doesn't work as I expect.

My idea is using fetch to send FormData (which contain an input has JSON as value) to the PHP. At the server side, PHP will take care the form with $_POST and return JSON string to me.

I'm using a free host service, which has PHP 7.0, for testing stuff.

All of the code below is in the same file (404.php):

var now = new Date();

var pkg = JSON.stringify({
    ts: now.getTime(),
    tz: now.getTimezoneOffset() / -60
})

var form = new FormData();
form.set('json', pkg);

console.log(form.has('json')) // true
console.log(form.values().next()) // return and obj contain JSON string

fetch('/404.php', {
    method: 'POST',
    body: form
});
$json = null;
if(isset($_POST['json'])) $json = json_decode($_POST['json']);

var_dump($_POST); //Result: array(0) { }

As you can see, the output of var_dump is an empty array. But what I expect to see is an output with a JSON string.

I've tried another way, which is this one fetch-api-json-php, but it also no use. All the resource I found on the Internet usually about the classic AJAX, not fetch API. And most of them are only for client side, there isn't much I could find for PHP/server side.

  • 写回答

2条回答 默认 最新

  • dongwen5019 2019-04-22 06:45
    关注

    Can you try to run this code in your local machine?

    Make a file name 55788817.php and paste this code and run.

      <?php
      if (isset($_POST) && !empty($_POST)) {
        $json = null;
        if(isset($_POST['json'])) $json = json_decode($_POST['json']);
    
        var_dump($_POST); //Result: array(1) { ["json"]=> string(29) "{"ts":1555915560755,"tz":5.5}" }
        exit;
      }
      ?>
      <!DOCTYPE html>
      <html>
      <head>
        <title></title>
      </head>
      <body>
        <button type="button" id="registerButton">Click Me!</button>
        <script>
          var now = new Date();
    
          var pkg = JSON.stringify({
              ts: now.getTime(),
              tz: now.getTimezoneOffset() / -60
          })
    
          var form = new FormData();
          form.append('json', pkg);
    
          console.log(form.has('json')) // true
          console.log(form.values().next()) // return and obj contain JSON string
          fetch('./55788817.php', {
              method: 'POST',
              body: form
          });
        </script>
      </body>
      </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗