PHP文件中获取数据返回空值
P粉617237727
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: &quot;POST&quot;, headers: { &quot;Content-type&quot; : &quot;application/json&quot; }, body: JSON.stringify({ username:&quot;Jonathan&quot;, email:&quot;jonathan@gmail.com&quot;, password:&quot;123456&quot; }) } fetch('Test.php',datos) .then(resp =&gt; resp.text()) .then(resp =&gt;{ console.log(resp); })</pre> <p><em><strong>Test.php</strong></em></p> <pre class="brush:php;toolbar:false;">&lt;script src=&quot;datosJS.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; //I use this to call &quot;datosJS.js&quot; to receive the data here in Test.php &lt;?php $body = json_decode(file_get_contents(&quot;php://input&quot;), true); var_dump($body); ?&gt;</pre> <p>我知道 PHP 在服务器端,JS 在客户端,并且它们都在不同的时间运行,但是我很难找到这个问题的解决方案。</p> <p>感谢您的帮助!</p> <p>** 编辑了 fetch 中的一个小更改,现在让我可以在控制台中查看数据</p>
P粉617237727
P粉617237727

全部回复(1)
P粉826283529

终于我设法解决了这个问题,解释如下:

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" 添加到 divsection 或其他内容从innerHTML接收。

我希望它对将来的人有所帮助。干杯

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号