You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch API/XMLHttpRequest向PHP传参报错:Undefined array key 'data' 如何解决?

解决PHP中Undefined array key 'data'的问题

问题场景

尝试用Fetch API或XMLHttpRequest发送POST请求,将JavaScript变量传递给PHP时,PHP文件中出现Undefined array key 'data'错误。相关代码如下:

HTML代码

<html>
<body>
 <textarea id="my-textarea"> </textarea>
 <button onclick="_post_text_area_()" id="submit-btn">Submit</button>
</body>
<html>

原Fetch API代码

// 获取文本框内容
var textarea = document.getElementById("my-textarea");

function _post_text_area_() {       
    var data = textarea.value;
    // 控制台打印文本框内容
    console.log(data);

    // 通过Fetch API发送POST请求
    fetch('_process.php', {
             method: 'POST',
             body: 'data=' + data
       })
       .then(function (response) {
          return response.text();
       })
       .then(function (data) {
           console.log(data);
           });
}

原XMLHttpRequest代码

var textarea = document.getElementById("my-textarea");

var submitBtn = document.getElementById("submit-btn");

submitBtn.addEventListener("click", function() {

  var data = textarea.value;

  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

      console.log(this.responseText); // 打印服务器返回内容

    }

  };

  xmlhttp.open("POST", "process.php", true);

  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xmlhttp.send("data=" + data);

});

PHP代码(_process.php)

<?php
$data = $_POST['data'];
echo "Received data: " . $data;
?>

错误原因

  1. Fetch请求未设置Content-Type头:发送application/x-www-form-urlencoded格式数据时,必须告知服务器请求体类型,否则PHP无法将数据解析到$_POST数组中。
  2. 数据未编码:若文本框内容包含特殊字符(如&、=、空格等),直接拼接会破坏数据格式,导致PHP解析失败。
  3. XHR请求文件名不一致:原XHR代码请求的是process.php,但实际处理文件名为_process.php,导致请求指向错误文件。

解决办法

1. 修正Fetch API代码

添加Content-Type请求头,并对数据进行URL编码:

function _post_text_area_() {       
    var data = textarea.value;
    console.log(data);

    fetch('_process.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'data=' + encodeURIComponent(data)
    })
    .then(function (response) {
        return response.text();
    })
    .then(function (responseData) {
        console.log(responseData);
    });
}

2. 修正XMLHttpRequest代码

修正请求文件名,并确保数据编码:

submitBtn.addEventListener("click", function() {
  var data = textarea.value;
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
  };

  xmlhttp.open("POST", "_process.php", true); // 修正文件名
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("data=" + encodeURIComponent(data)); // 编码特殊字符
});

3. PHP端添加安全校验

避免未接收到数据时抛出错误,先检查$_POST['data']是否存在:

<?php
if(isset($_POST['data'])) {
    $data = $_POST['data'];
    echo "Received data: " . $data;
} else {
    echo "No data received";
}
?>

内容的提问来源于stack exchange,提问作者user14552956

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:36:59