PAYATHON 2026

JavaScript 使用 fetch 和 XHR 提交数据后,PHP 的 $_POST 为什么为空?

数据小陈

结论

原代码有几处独立问题:fetch 读取的是表单元素的 value,没有读到输入框内容;XHR 第二次调用 open() 把请求方法改成了 GET;FormData 在点击按钮前就已创建,无法反映之后输入的值。PHP 也不会自动将 JSON 请求体放进 $_POST。

建议先保留一种请求方式:提交时创建 FormData,通过 POST 发送,PHP 用 $_POST['testInput'] 读取,再由 JavaScript 将响应写入页面。

fetch 是异步 API,xhr.open(..., true) 同样表示异步请求。实现无刷新提交不需要使用同步请求。

为什么原代码收不到预期数据

1. tef.value 没有读取输入框

tef 指向的是 <form>,不是其中的输入框:

let tef = document.getElementById("testForm");
var variableValue = tef.value;

在给出的 HTML 中,tef.value 是 undefined。如果需要单独读取输入框,可以使用:

const variableValue = document.getElementById("testInput").value;

读取操作应放在提交事件中,否则保存的是脚本执行时的值。

原代码中,JSON 序列化会省略对象里值为 undefined 的属性,因此实际生成的是空对象字符串:

JSON.stringify({ testForm: undefined }); // "{}"

2. 第二次 open() 将 POST 改成了 GET

这两行不会分别创建两个请求:

xhr.open("POST", "/file.php", true);
xhr.open("GET", "/file.php", true);

第二次调用会重新初始化同一个 XHR,最后发送的是 GET。GET 请求会忽略传给 send() 的请求体,因此 formData 不会按预期作为 POST 表单数据发出。

3. FormData 创建得太早

var formData = new FormData(tef);

这行代码位于点击事件外。FormData 保存的是创建时表单中可提交字段的值,用户之后输入的内容不会自动更新到这个对象中。

应在用户提交时重新创建:

const formData = new FormData(tef);

原输入框具有 name="testInput",对应的 PHP 键名是 testInput。表单的 id="testForm" 不会自动成为提交字段。

4. JSON 请求体不会自动进入 $_POST

PHP 的 $_POST 用于接收 POST 请求中的常规表单数据,常见编码包括 application/x-www-form-urlencoded 和 multipart/form-data。

发送 JSON 时,PHP 需要读取原始请求体,再调用 json_decode()。即使请求方法是 POST,JSON 内容也不会自动进入 $_POST。

发送 FormData 时不要手动设置 Content-Type。浏览器需要生成包含 boundary 的 multipart/form-data 请求头。原代码设置的 application/x-www-form-urlencoded 与 FormData 的实际编码不匹配。

使用 fetch 完成无刷新提交

下面的示例假设 HTML 页面与 file.php 位于同一目录,且 PHP 文件能够通过 Web 服务器执行。

HTML 和 JavaScript:

<form id="testForm" action="file.php" method="post">
  <input type="text" id="testInput" name="testInput">
  <button type="submit" id="testBtn">Test Button</button>
</form>

<pre id="result" aria-live="polite"></pre>

<script>
const form = document.getElementById("testForm");
const result = document.getElementById("result");

form.addEventListener("submit", async (event) => {
  event.preventDefault();

  const formData = new FormData(form);

  try {
    const response = await fetch(form.action, {
      method: "POST",
      body: formData
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    result.textContent = await response.text();
  } catch (error) {
    result.textContent = `请求失败:${error.message}`;
    console.error(error);
  }
});
</script>

file.php:

<?php
header('Content-Type: text/plain; charset=utf-8');

$value = $_POST['testInput'] ?? '';

if (!is_string($value)) {
    http_response_code(400);
    echo 'testInput 必须是字符串';
    exit;
}

$processedValue = trim($value);
echo 'PHP 处理后的值:' . $processedValue;

代码在提交时读取当前表单内容,PHP 收到后执行 trim(),前端再将响应显示到 result 元素中。调试时也可以在 PHP 中临时使用 print_r($_POST); 查看字段。

event.preventDefault() 用来阻止表单默认提交造成页面跳转。原代码的 <input type="button"> 本身不会触发表单默认提交,因此添加 return false; 无法修复取值和请求体的问题。

如果使用 XHR

可以将上面的 fetch 提交事件处理器替换为以下代码,保留相同的表单、结果元素和 PHP 接收逻辑:

const form = document.getElementById("testForm");
const result = document.getElementById("result");

form.addEventListener("submit", (event) => {
  event.preventDefault();

  const xhr = new XMLHttpRequest();
  xhr.open("POST", form.action, true);

  xhr.onload = () => {
    if (xhr.status >= 200 && xhr.status < 300) {
      result.textContent = xhr.responseText;
    } else {
      result.textContent = `请求失败:HTTP ${xhr.status}`;
    }
  };

  xhr.onerror = () => {
    result.textContent = "请求失败:网络错误";
  };

  xhr.send(new FormData(form));
});

每次提交都会创建新的 XHR,只调用一次 open(),并让浏览器设置 FormData 所需的请求头。调试时不要同时保留 fetch 和 XHR 两套提交逻辑,否则一次操作会产生两个请求。

如果确实要发送 JSON

前端可以发送 JSON:

const response = await fetch("file.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    testInput: document.getElementById("testInput").value
  })
});

此时 PHP 应改为读取 php://input,不再从 $_POST 获取这个字段:

<?php
header('Content-Type: text/plain; charset=utf-8');

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

if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
    http_response_code(400);
    echo '无效的 JSON 请求体';
    exit;
}

$value = $data['testInput'] ?? null;

if (!is_string($value)) {
    http_response_code(400);
    echo 'testInput 必须是字符串';
    exit;
}

echo 'PHP 处理后的值:' . trim($value);

前后端需要使用一致的字段名。发送 testInput,就读取 testInput;如果选择 testForm 作为 JSON 属性名,PHP 也必须读取对应属性。

为什么 echo 没有直接出现在页面上

fetch 或 XHR 请求的响应会交给 JavaScript。PHP 的 echo 只会写入这次请求的响应体,不会自动修改当前页面的 DOM。

原代码只调用了 alert(txt) 和 console.log(xhr.responseText),所以结果只会出现在提示框和控制台里。要显示到页面,需要显式更新元素,例如:

result.textContent = txt;

这里用 textContent 显示纯文本,用户输入不会被当作 HTML 解析。

如果修改后仍有问题,可以在浏览器开发者工具的 Network 面板检查请求方法、最终 URL、请求体和响应内容。原表单的 file.php 是相对路径,而 JavaScript 的 /file.php 指向站点根目录;页面位于子目录时,两者可能不是同一个地址。现有材料不足以认定问题由 WordPress 引起,应先确认请求确实到达了预期的 PHP 处理文件。

备注:内容仅供参考。