PHP文件中获取数据返回空值
                
                    
                         
                        
                            
                                P粉617237727
                                2023-08-30 11:20:14
                            
                                                        [PHP讨论组]
                                                     
                     
                    
                 
             
            
            
                <p>我正在尝试测试和学习 fetch 的工作原理,所以我想将一些数据从 javascript 发送到 php 文件,我的问题是我无法检索数据(在 php 文件中),只能得到 null回应。</p>
<p>我正在使用 POST,但我尝试使用 GET 得到了相同的结果</p>
<p>作为旁注,在控制台中,网络中的连接仅在我按 F5 后出现,据我了解,当我打开 Test.php 时应该已经开始工作。</p>
<p><em><strong>datosJS.js</strong></em></p>
<pre class="brush:php;toolbar:false;">let datos = {
   method: "POST",
   headers: {
            "Content-type" : "application/json"
   },
   body: JSON.stringify({ 
      username:"Jonathan",
      email:"jonathan@gmail.com",
      password:"123456"
  })
}
fetch('Test.php',datos)
.then(resp => resp.text())
.then(resp =>{
    console.log(resp);
})</pre>
<p><em><strong>Test.php</strong></em></p>
<pre class="brush:php;toolbar:false;"><script src="datosJS.js" type="text/javascript"></script> //I use this to call "datosJS.js" to receive the data here in Test.php
<?php
 $body = json_decode(file_get_contents("php://input"), true);
    var_dump($body);
    
?></pre>
<p>我知道 PHP 在服务器端,JS 在客户端,并且它们都在不同的时间运行,但是我很难找到这个问题的解决方案。</p>
<p>感谢您的帮助!</p>
<p>** 编辑了 fetch 中的一个小更改,现在让我可以在控制台中查看数据</p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
            
            
            
            
            
         
     
终于我设法解决了这个问题,解释如下:
datosJS.js
window.onload = function() { let datos = { method: "POST", headers: { "Content-type" : "application/json" }, body: JSON.stringify({ username:"Jonathan", email:"jonathan@gmail.com", password:"123456" }) } fetch('Test.php',datos) .then(resp => resp.text()) .then(resp =>{ console.log(resp); document.getElementById('results').innerHTML = resp; //document.querySelector('#results').innerHTML = resp; // works as well as getElementById }) }测试.php
<script src="datosJS.js" type="text/javascript"></script> <section class="Section" id="results" name="results"> <?php $body = json_decode(file_get_contents("php://input"), true); $nombre = $body['username']; echo $nombre; echo '</br>'; print_r($body); ?>下面我会标出原代码中缺少的内容:
在 datosJS.js 中 document.getElementById('results').innerHTML = resp; 并将所有内容包装在 window.onload = function() {} 中
在 Test.php 中将 id="results" name="results" 添加到 div、section 或其他内容从innerHTML接收。
我希望它对将来的人有所帮助。干杯