PHP檔案中取得資料傳回空值
P粉617237727
P粉617237727 2023-08-30 11:20:14
0
1
450
<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>
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接收。

我希望它對將來的人有幫助。乾杯

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!