我正在使用 fetch api 方法将 javascript 变量传递给 php,但在 php 生活中出现错误:未定义的数组键“数据”。如何解决?

问题描述 投票:0回答:1

-----html代码-----

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

-----javascript代码-----

# get value of textarea
var textarea = document.getElementById("my-textarea");

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

    # pass data variable using fetch api POST method
    fetch('_process.php', {
             method: 'POST',
             body: 'data=' + data
       })
       .then(function (response) {
          return response.text();
       })
       .then(function (data) {
           console.log(data);
           });
}

--- _process.php ---

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

我在 _process.php 文件中收到错误:未定义的数组键“数据”。我想,我收到此错误是因为我的 javascript 函数无法创建发布请求,但我不知道收到此错误的确切原因。

我尝试了不同的技术,如 ajax XmlHttpRequest 将数据变量传递给 _process.php 文件,但我遇到了同样的错误。

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); // Print the response from the server

    }

  };

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

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

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

});


javascript php html server-side client-side
1个回答
0
投票

在创建要通过

FormData
发送的有效负载时,通常首选使用
fetch
——以下确实发送了AJAX请求,但由于沙盒限制而失败。

const d=document;

document.addEventListener('click',e=>{
  if( e.target instanceof HTMLButtonElement && e.target.id=='submit-btn' ){
    let fd=new FormData();
    fd.set('data', d.getElementById("my-textarea").value );

    fetch('_process.php', {method:'post',body:fd })
      .then(r=>r.text())
      .then(console.log)
      .catch(alert)
  }
});
<textarea id="my-textarea"></textarea>
<button id="submit-btn">Submit</button>

© www.soinside.com 2019 - 2024. All rights reserved.