首页 > 解决方案 > 另一个 $_POST 没有从 Javascript 的 Fetch() 中检索数据(但 ajax 确实...)(已解决)

问题描述

已解决:我忘记将数据添加到 fetch...

我终于迈出了 ajax & co 的一步...查找了这些东西,并想使用更新的 fetch 机制,但这没有用....服务器端的 $_POST 仍然令人沮丧地空着。 ...我切换到 ajax,使用相同的服务器,几乎相同的代码,它可以工作!

所以我有一个可行的解决方案,但是,知道应该起作用的东西却不令人满意,但……如果有人有解决方案?

让我们从 php 模型开始:

 testsave.php:
 
 <?php
   print("POST = ".print_r($_POST,true));
   print("inputstream :".file_get_contents('php://input')."\n");//maybe here??
 ?>

和test.php:

<html>
 <header>
  <link rel="icon" href="favicon.svg">
 </header>
 <body>
  <form  method="post" onsubmit="return withajax('testsave.php','testfield');">
   <input type="text" id="testfield"/>
   <input type="submit" value="ok"/>
  </form>
  <script> 
     function withajax(filename, fieldname)
     {
        let data = new FormData();
        data.append(fieldname, document.getElementById(fieldname).value);

        var xhr = new XMLHttpRequest();
        xhr.open("POST", filename);
        xhr.onload = function()
        {
          document.getElementById(fieldname).value = this.response;
          console.log(this.response);
        };
        xhr.send(data);
        return false;
     }//function withajax(filename)

     function withfetch(filename, fieldname)
     {
       let data = new FormData();
       data.append(fieldname, document.getElementById(fieldname).value);
       let configObj =
       {
         method: "POST",
         //cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
         //credentials: 'same-origin', // include, *same-origin, omit
         body: data
       };
       fetch(filename,configObj) //<-- edit without adding the data, it won't work.... 
      .then(function (response) 
       {
         return response.text();
       })
      .then(function (text) 
      {
        document.getElementById(fieldname).value = text;
        console.log("response = "+text);

      })
     .catch(function (error) 
     {
             console.log("Error : "+error);
      });
      return false; 
   }//function withfetch(filename)
 </script>
 </body>
 </html>
                         

如果在表单的onsubmit中我放了withajax,它就可以工作,如果我放withfetch,php脚本中的$_POST中什么都没有......

标签: javascriptphpfetch

解决方案


推荐阅读