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

为什么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.

图片转代码服务由CSDN问答提供 功能建议

我想将JSON数据(在本例中是客户端时间戳)发送到我的服务器。 但是,我的代码似乎无法正常工作。

我的想法是使用fetch将PHP发送FormData(其中包含一个输入有JSON值)。 在服务器端,PHP将使用 $ _ POST 处理表单并将JSON字符串返回给我。

我正在使用免费的主机服务,它具有 PHP 7.0,用于测试内容。

下面的所有代码都在同一个文件中(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和obj包含JSON字符串
 
fetch('/ 404.php',{
方法:'POST',
 body:form 
}); 
   \  n 
 
  $ json = null; 
if(isset($ _ POST ['json']))$ json = json_decode($ _ POST ['json']  ); 
 
var_dump($ _ POST);  //结果:array(0){} 
 
   
 
 

如您所见,var_dump的输出是一个空数组。 但我期望看到的是带有JSON字符串的输出。

我尝试了另一种方法,就是这个 fetch-api-json-php ,但它也没用。 我在互联网上找到的所有资源通常都是关于经典的AJAX,而不是fetch API。 其中大多数只是客户端,我找不到很多PHP /服务器端。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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>
    
    已采纳该答案
    打赏 评论
  • douchaqi3369 2019-04-22 05:46

    This worked for me:

    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script>
        var pkg = '{"test":"data"}';
        var formData = new FormData();
        formData.set('json', pkg);
    
        fetch('./404.php', {
          method: 'POST',
          body: formData
        });
    </script>
    </head>
    <body>
    
    </body>
    </html>
    

    PHP:

    <?php
    $json = null;
    if(isset($_POST['json'])) 
        $json = json_decode($_POST['json']);
    
    var_dump($_POST, $json); 
    
    // Result: array(1) { ["json"]=> string(15) "{"test":"data"}" } object(stdClass)#1 (1) { ["test"]=> string(4) "data" } 
    
    ?>
    
    打赏 评论