簡體   English   中英

數據未使用獲取API發送到服務器

[英]Data is not sent to server using fetch api

我正在使用訪存API與服務器進行交互。 我正在嘗試將數據發送到服務器。 我的前端代碼如下所示:

<!DOCTYPE html>
<html>
<head>
  <title> Fetch Testing </title>
</head>
<body>
  <button id = "add"> Add </button>

  <script>
    document.getElementById("add").addEventListener("click", function(){
      var options = {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({name: "george", email: "george@g.com"})
      };

      fetch("get.php",options)
      .then(function(response){
        console.log(response);
      });
    });

  </script>
</body>
</html>

我的服務器端代碼(稱為“ get.php”)如下所示:

<?php
  echo var_dump($_POST);
?>

如您所見,我正在發送帶有屬性名稱和電子郵件及其值的json,但是似乎沒有任何內容發送到服務器,因為打印響應會給出null json和null文本。

將響應的標題設置為json get.php:

header('Content-Type: application/json');
echo json_encode($_POST);

問題出在標題中,我應該寫成Content-type

application / x-www-form-urlencoded;

代替

應用程序/ json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM