【问题标题】:How can I read fetch() form data in php?如何在 php 中读取 fetch() 表单数据?
【发布时间】:2021-03-03 21:30:27
【问题描述】:

我有这段代码对我有用,但是当我尝试在 PHP 中实际使用表单数据时,我无法让它工作。我已经从堆栈溢出和网络尝试了许多 sn-ps,但似乎没有任何效果。我做了一个简化的测试用例,发现我无法使用var_dump($_POST),因为我一定对 fetch 的工作方式有一些误解,因为当我用 var_dump($_POST) 甚至 echo("test") 替换 php 文件时,我'我什么都没看到。

谁能帮我获取发送到 php 文件的数据?

checkout.html(这很好用)

<!DOCTYPE html>
<html>
  <head>
    <title>Buy cool new product</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
  </head>
  <body>
    <section>
      <form id = "myForm">
        <input type="text" name="">
        <input type="submit" name="">
      </form>
    </section>
  </body>
  <script type="text/javascript">
    // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe("pk_9999999999999999999");
    
const myForm = document.getElementById('myForm');


    myForm.addEventListener("submit", function (e) {
      e.preventDefault();

      const formData = new FormData(this);

      fetch("/create-checkout-session-dump.php", {
        method: "POST",
        body: formData
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
          // If redirectToCheckout fails due to a browser or network
          // error, you should display the localized error message to your
          // customer using error.message.
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
  </script>
</html>

creatch-checkout-session-dump.php(这只是代替常规文件作为简化的测试用例 - 原始文件适用于我想要的,但我需要能够以某种方式在这里看到表单内容,但因为它是我什至无法得到它所以打印“hello world”)

<?php
echo('test');

【问题讨论】:

  • 您在寻找$_POST 吗?
  • 您的表单输入没有名称。未发送未命名的输入。
  • return response.json() 如果你给它一个 var_dump 而不是 JSON,将会出错。
  • “我什至无法得到它,所以打印“hello world””——你希望它在哪里打印它到?你在看哪里?
  • 昆汀我认为回声会像正常回声一样打印到屏幕上——我真的不明白这有什么不同

标签: php forms fetch


【解决方案1】:

我会在这里再次回答你。

在您的 PHP 文件中,您最好使用 $_POST 超级全局变量。

<?php

$data = $_POST['test'];

?>

此“测试”键标记与您在表单中命名输入/值的任何内容直接相关。试试这个:

<input type="text" name="test" />

<script>

fetch("/create-checkout-session-dump.php",{
    type: "POST",
    body: formData
    })
    .then( response => response.ok ? response.json() : "ERROR LOADING" )
    .then( data => console.log(data) )
    .catch( err => console.error(err) );

</script>

【讨论】:

  • 这基本上是我最后所做的,所以给你打勾
  • 这是我之前所说的,但有人很不高兴我添加了更多信息。请记住,您可以对其进行一些重构,并将 console.log(data) 返回仅删除为数据,以便您可以以更健壮的方式操纵 fetch 返回。
猜你喜欢
  • 2016-08-18
  • 2020-09-19
  • 1970-01-01
  • 2020-05-14
  • 2019-06-08
  • 2012-05-27
  • 2019-07-21
  • 2017-02-09
  • 1970-01-01
相关资源
最近更新 更多